Kaprekar's constant in C++

 Kaprekar's constant in C++



/*

The number 6174 is known as Kaprekar's constant. It is the ultimate convergence point of the Kaprekar's routine, an algorithm thought up by Indian mathematician D.R. Kaprekar in 1949.

The routine is as follows:
1. Take any four-digit number (at least two different digits must be used, zeroes allowed).
2. Arrange the digits in descending and then in ascending order to get two four-digit numbers.
3. Subtract the smaller number from the larger and get the result.
4. Repeat steps 2-4 with the new number.

After a few iterations, the algorithm converges to a fixed point and starts to result in the same number  - 6174 - the so-called Kaprekar's constant.

For Example:
n = 5324

5432 - 2345 = 3087
8730 - 0378 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174

For numbers beyond four digits the routine might converge to 0 (zero), other constants or "loops" (infinitely repetitive sequences of the same numbers over and over again).
*/

#include<iostream>
#include<iomanip>
using namespace std;

void Sort(int *a,int n)
{
 int i,j,temp;
 for(i=0;i<n;i++)
 { 
  for(j=i+1;j<n;j++) 
  {
   if(a[i]>a[j]) 
   {
    temp=a[i]; 
    a[i]=a[j]; 
    a[j]=temp;
   }
  }
 } 

}

void Kaprekar(int num)
{
 static int counterT,counterK;
 counterT++;
 int a[5],ans,c,i;
  
 int n=num; c=0;
 while(n!=0)
 {
  a[c++]=n%10;
  n=n/10;   
 }

 Sort(a,c);

 int num1=0;
 for(i=c-1;i>=0;i--)
   num1=num1*10+a[i];

 int num2=0; 
 for(i=0;i<c;i++)
  num2=num2*10+a[i];

 ans=num1-num2;
 cout<<num1<<" - "<<setw(4)<<num2<<" = "<<ans<<endl;

 if(ans==6174 || ans==495)
   counterK++;
   
 if(counterK==2){
   cout<<"\nIterator : "<<counterT;
   cout<<"\nKAPREKAR's Constant Reached.";
 }
 else
  Kaprekar(ans);

}

int main()
{
 int num;
// cout<<" Enter your number\n";
 cin>>num;
 cout<<"Entered number : "<<num<<endl<<endl; 
 Kaprekar(num);
 return 0;
}

Post a Comment

Previous Post Next Post