/* * To print all Kaprekar numbers in the range 1 to 999. * Consider an n-digit positive integerr k. Square it and add the right n digits * to the left n or n-1 digits. If the resultant sum of either is k, then k is * called a Kaprekar number. * To be compiled using: gcc -lm * For example,if your filename is kaprekar.c,compile it using: gcc -lm kaprekar.c * @author-Karan Narain(karan@iitk.ac.in) * */ #include #include //Function to count the number of digits int num_digits(int k) { int dig=0; while(k>0) { k=k/10; dig++; } return dig; } int isKaprekar(int k) { int n,square,square_digits,sum=0,right_n,left,p; n=num_digits(k); square=pow(k,2); square_digits=num_digits(square); p=pow(10,n); //right n digits right_n=square%p; //if the value of right n digits is 0,then it cannot be a kaprekar number. //eg.square of 100 is 10000,still 100 is not a kaprekar number since the right n-digits of 10000 represent 0 if(right_n==0) return 0; left=square/p; sum=(right_n + left); if(sum==k) return 1; //if the square has 2n-1 digits,then we should check for the sum of left n digits with the right n digits as well(there will be an overlap) if(square_digits==((2*n)-1)) { p=pow(10,n-1); left=square/p; sum=(right_n + left ); if(sum==k) return 1; else return 0; } } int main() { int i; printf("\nPrinting the list of Kaprekar numbers from 1 to 999...\n"); for(i=1;i<=999;i++) { if(isKaprekar(i)==1) printf("%d\n",i); } return 0; }