A 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 p, int q){int flag = 0;for (long int i = p; i <= q; i++){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(10, a);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(p, q);return 0;}
No comments:
Post a Comment