Home > database >  Checking If A Number Is Kaprekar
Checking If A Number Is Kaprekar

Time:12-13

I'm writing a program to check if a number that the user inputs is a kaprekar number (a number that's square can be split up and added to get the original number) however I can only write a program that really only works for 1 & 2 digit squares (1 & 1 and 9 & 81), here is my code:

double kaprekarNum = 0;
kaprekarNum = int.Parse(Console.ReadLine());

double kmSqr = Math.Pow(kaprekarNum, 2);
string kmSqrString = kmSqr.ToString();

double[] kmSqrDouble = new double[kmSqrString.Length];

for(int i = 0; i < kmSqrString.Length; i  )
{
    kmSqrDouble[i] = int.Parse(kmSqrString[i].ToString());
    kapTest = kapTest   kmSqrDouble[i];
}

if(kapTest == kaprekarNum)
{
    Console.WriteLine("{0} is a kaprekar.", kaprekarNum);
}
else if(kapTest != kaprekarNum)
{
    Console.WriteLine("{0} is not a kaprekar.", kaprekarNum);
}

As you can see, the program is splitting the number up into 1 digits, which is not what I want. I need it to split it up into every possible way and then add it up but I don't know how to go through with this. How would you do this?

CodePudding user response:

I would avoid using double. Here's a simple implementation. I think you have made a mistake looping over your string instead of slicing it into the left and right segments:

int testNbr = 297;

//beware overflow potential
int testSqrd = testNbr*testNbr;

string testSqrdStr = testSqrd.ToString();

// The right-most testNbr.Length digits from the squared value
string right = testSqrdStr.Substring(testSqrdStr.Length - testNbr.ToString().Length);

// The left most remaining
string left = testSqrdStr.Substring(0, testSqrdStr.Length - right.Length);

int result = int.Parse(right)   int.Parse(left);

bool isKaprekar = testNbr == result;
  • Related