Kaprekar Number - GeeksforGeeks
A Kaprekar number is a number whose square when divided into two parts and such that sum of parts is equal to the original number and none of the parts has value 0. (Source : Wiki)
Given a number, the task is to check if it is Kaprekar number or not.
Read full article from Kaprekar Number - GeeksforGeeks
A Kaprekar number is a number whose square when divided into two parts and such that sum of parts is equal to the original number and none of the parts has value 0. (Source : Wiki)
Given a number, the task is to check if it is Kaprekar number or not.
- Find square of n and count number of digits in square.
- Split square at different positions and see if sum of two parts in any split becomes equal to n.
bool iskaprekar(int n){ if (n == 1) return true; // Count number of digits in square int sq_n = n * n; int count_digits = 0; while (sq_n) { count_digits++; sq_n /= 10; } sq_n = n*n; // Recompute square as it was changed // Split the square at different poitns and see if sum // of any pair of splitted numbers is equal to n. for (int r_digits=1; r_digits<count_digits; r_digits++) { int eq_parts = pow(10, r_digits); // To avoid numbers like 10, 100, 1000 (These are not // Karprekar numbers if (eq_parts == n) continue; // Find sum of current parts and compare with n int sum = sq_n/eq_parts + sq_n % eq_parts; if (sum == n) return true; } // compare with original number return false;}