Tuesday, June 16, 2020

Kaprekar Number

Consider an n-digit number k. Square it and add the right n digits to the left n or n-1 digits.If the resultant sum is k, then k is called a Kaprekar number.
For example, 9 is a Kaprekar number since 9^2 = 81 & 8 + 1 = 9 , 297 is a Kaprekar number

as 297^2 = 88209 & 88 + 209 = 297 Write a program to find whether the given number is a Kaprekar number or not.

INPUT & OUTPUT FORMAT:
Input consists of a single integer.

Refer sample output for details.

SAMPLE INPUT:
9

OUTPUT:
Kaprekar Number

SOLUTION:

#include<iostream>
using namespace std;
int main()
{
  int k,n,r,s,sum1,sum2,c,temp,l,sum,a;
  a=1;
  cin>>k;
  n = 0;
  sum1 = 0;
  sum2 = 0;
  temp = k;
  s = k*k;
  do{
++n;
temp /= 10;
  }while(temp>0);
  
  for(c = 0; c < n; c++){
  r = s % 10;
  s = s/10;//8 
sum1 = sum1 + r*a;
a*=10;
  }
  a=1;
  while(s>0){
  r = s %10;
  s = s/10;
sum2 = sum2 +r*a;
a*=10;
  }
  sum  = sum1 + sum2;
  if(sum == k){
  cout<<"Kaprekar Number";  
  }
  else{
  cout<<"Not a Kaprekar Number";
  }  
}

No comments:

Post a Comment

horizontal ads