Kaprekar number

Given number base is a -Kaprekar number if the representation of its square in that base can be split into two parts, where the second part has digits, that add up to the original number.


Write a program to determine Kaprekar number


For Example

Input
 9
Output
Kaprekar number 

i.e. 92 = 81 then 8+1 =9

Solution:

using System;

namespace KaprekarNumber
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter a number:");
            var num = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(IsKaprekarNumber(num) ? "Kaprekar Number" : "Not a Kaprekar Number");
            Console.ReadLine();
        }

        static bool IsKaprekarNumber(int n)
        {
            if (n == 1)
                return true;
            var square = n * n;
            var counter = 0;
            while (square  != 0)
            {
                counter++;
                square  /= 10;
            }

            square  = n * n;
            for (var i = 1; i < counter; i++)
            {
                var pow = (int)Math.Pow(10, i);
                if (pow == n)
                    continue;

                var sum = (square  / pow) + (square  % pow);
                if (sum == n)
                    return true;
            }
            return false;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *