Home / C / C program for Kaprekar number

C program for Kaprekar number

Here is given c program for Kaprekar number.

But before what exactly is a Kaprekar number?

A Kaprekar number is a number whose square can be broken/partitioned in such a manner that the sum of the partitions adds up to bring the number itself.

Example: 992 = 9801 : 98+01 = 99  (hence kaprekar)

// This program is however limited to check untill 99999 because long int has a range of 0 – 4294967296 and 999992 is greater than that

Also Check: Java program for kaprekar number

#include <stdio.h>

unsigned long int digitcount(long int x)
{ unsigned long int digit=0;
	while(x)
	{
	digit++;
	x/=10;
	}
return digit;
}

unsigned long int return_A(long int x)
{
	while(x%10==0)
	x/=10;
return x;
}

unsigned long int div(long int x)
{
unsigned long int num=1;
while(x--)
num*=10;
return num;
}

 int main()
{
unsigned long int n,A,B,digits,sq,temp;

printf("Enter number to find whether it is a Kaprekar number or not : ");
scanf("%ld",&n);

sq=n*n;
//count the number of digits in the square of that number
digits=digitcount(sq);

//now partition the square number using X=Ab^n + B ; where b=10 (decimal number system)
// partitioning theory is written above
A= sq/ div(digits/2);	//But this will get Ab^n  so remove b^n:-
A=return_A(A);
B= sq% div(digits/2);
temp=A+B;
if(temp==n)
printf("\n It is a Kaprekar number");
else
printf("\n Not a kaprekar number");
return 1;
}

OUTPUT:

c program for kaprekar number
program for Kaprekar number

Incoming terms: C program for kaprekar number, c program to check whether it is a kaprekar number or not.

Check Also

Restrict Mouse Pointer Position C Graphics Program

This C Program will restrict the Mouse Pointer location or to a particular position or x,y ...