Skip to main content
  1. Problem Solving Solutions/

Kaprekar Number

·2 mins
Problem Solving
Mayukh Datta
Author
Mayukh Datta
Table of Contents

Wikipedia says, “in mathematics, a non-negative integer is called a “Kaprekar number” for a given base if the representation of its square in that base can be split into two parts that add up to the original number, with the proviso that the part formed from the low-order digits of the square must be non-zero—although it is allowed to include leading zeroes.”

\(55\) is a Kaprekar number because if we do \(55^2 = 3025\) and split \(3025\) into \(30, 25\) and sum the two parts it turns out to be \(55\) itself. Similarly, \(4879\) is also a kaprekar number. \(4879^2 = 23804641\) and parts \((238, 04641)\) sum up to \(4879\).

C++ code:

#include #include using namespace std;

bool check_kaprekar(long k);

int main(void){ long n; cout«“Enter a no.: “; cin»n; if(check_kaprekar(n)){ cout«n«” is a Kaprekar Number."«endl; }else{ cout«n«” is not a Kaprekar Number.\n"; } return 0; }

bool check_kaprekar(long k){ /** 1^2 = 01 0 + 1 = 1 **/ if(k==1) return true;

//find n^2
unsigned long long sqr = k \* k;
//find the count of digits
int len = floor(log10(sqr)) + 1;
//split sqr at different points and check if sum equals to k
for(int j=1;j<len;j++){
    int point = pow(10, j); //point is multiples of 10

    if(point == k){
        //multiples of 10 are not kaprekar nos.
        continue;
    }
    long sum = (sqr / point) + (sqr % point);
    if(sum == k)
        return true;
}
return false;

}

Related: #