Modified Kaprekar Numbers

modified Kaprekar number is a positive whole number with a special property. If you square it, then split the number into two integers and sum those integers, you have the same value you started with.

Consider a positive whole number n with d digits. We square n to arrive at a number that is either 2Xd digits long or  digits long. Split the string representation of the square into two parts,  and . The right hand part,  must be  digits long. The left is the remaining substring. Convert those two substrings back to integers, add them and see if you get .

Example:

Input:  p = 1, q = 100
Output: 1 9 45 55 99 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void kaprekarNumbers(int pint q)
{
    int flag = 0;

    for (long int i = pi <= qi++)
    {
        long int sum;
        long int a = 0;
        long int k = i;
        while (k > 0)
        {
            k /= 10;
            ++a;
        }
        long int n = i * i;
        long int g = pow(10a);
        sum = n % g + n / g;
        if (sum == i)
        {
            cout << sum << " ";
            flag++;
        }
    }
    if (flag == 0)
        printf("INVALID RANGE");
}

int main()
{

    int p = 1;
    int q = 100;

    kaprekarNumbers(pq);

    return 0;
}


No comments:

Post a Comment