# Modified Kaprekar Numbers – HackerRank Solution

In this post, we will solve Modified Kaprekar Numbers HackerRank Solution. This problem (Modified Kaprekar Numbers) is a part of HackerRank Problem Solving series.

Contents

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Â 2 x dÂ digits long orÂ (2 x d) – 1Â digits long. Split the string representation of the square into two parts,Â lÂ andÂ r. The right hand part,Â rÂ must beÂ dÂ digits long. The left is the remaining substring. Convert those two substrings back to integers, add them and see if you getÂ n.

Example

n = 5
d = 1

First calculate thatÂ n2 = 25. Split that into two strings and convert them back to integersÂ 2Â andÂ 5. TestÂ 2 + 5 = 7 != 5, so this is not a modified Kaprekar number. IfÂ n = 9, stillÂ d = 1, andÂ n2 = 81. This gives usÂ 1 + 8 = 9, the originalÂ n.

Note: r may have leading zeros.

Here’s an explanation from Wikipedia about theÂ ORIGINALÂ Kaprekar NumberÂ (spot the difference!):

``In mathematics, a Kaprekar number for a given base is a non-negative integer, the representation of whose square in that base can be split into two parts that add up to the original number again. For instance, 45 is a Kaprekar number, because 45Â² = 2025 and 20+25 = 45.``

Given two positive integersÂ pÂ andÂ qÂ whereÂ pÂ is lower thanÂ q, write a program to print the modified Kaprekar numbers in the range betweenÂ pÂ andÂ q, inclusive. If no modified Kaprekar numbers exist in the given range, printÂ `INVALID RANGE`.

Function Description

Complete the kaprekarNumbers function in the editor below.

kaprekarNumbers has the following parameter(s):

• int p: the lower limit
• int q: the upper limit

Prints

It should print the list of modified Kaprekar numbers, space-separated on one line and in ascending order. If no modified Kaprekar numbers exist in the given range, printÂ `INVALID RANGE`. No return value is required.

## Input Format

The first line contains the lower integer limitÂ p.
The second line contains the upper integer limitÂ q.

Note: Your range should be inclusive of the limits.

## Constraints

• 0 < p < q < 100000

Sample Input

``````STDIN   Function
-----   --------
1       p = 1
100     q = 100``````

Sample Output

``1 9 45 55 99``

Explanation

1,Â 9,Â 45,Â 55, andÂ 99Â are the modified Kaprekar Numbers in the given range.

## Solution – Modified Kaprekar Numbers – HackerRank Solution

### C++

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
long long p;
long long q;
cin>>p;
cin>>q;
vector<long long> res;
for(long long i=p; i<=q; ++i){
long long sq = i*i;
string s = to_string(sq);
int d = s.size()/2;
if(d == 0){
if(i == sq){
res.push_back(i);
}
continue;
}
if(stoll(s.substr(0,d))+stoll(s.substr(d,s.size()-d)) == i){
res.push_back(i);
}
}
if(res.size()>0){
for(int i=0; i<res.size(); ++i){
cout<<res[i]<<" ";
}
cout<<endl;}
else{
cout<<"INVALID RANGE"<<endl;
}
return 0;
}```

### Python

```import sys

def is_kaprekar(num):
if num < 4:
if num == 1:
return True
else:
return False
num_sq = pow(num, 2)
num_sq_str = str(num_sq)

left = num_sq_str[:len(num_sq_str)//2]
right = num_sq_str[len(num_sq_str)//2:]

#print("left = {} right = {}".format(left, right))

if int(left) + int(right) == num:
return True
else:
return False

def kaprekarNumbers(p, q):
out = []
for num in range(p, q + 1):
if is_kaprekar(num):
out.append(num)
return out

if __name__ == "__main__":
p = int(input().strip())
q = int(input().strip())
result = kaprekarNumbers(p, q)
if result:
print (" ".join(map(str, result)))
else:
print("INVALID RANGE")
```

### Java

```import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) throws Exception {

Scanner sc = new Scanner(System.in);
int p = sc.nextInt();
int q = sc.nextInt();
boolean isFirst = true;
for(int i = p; i <= q; i++)
if(isKaprekar(i)) {
System.out.printf((isFirst) ? "%d" : " %d", i);
isFirst = false;
}
System.out.println((isFirst) ? "INVALID RANGE" : "");
}

public static boolean isKaprekar(long a) {
int d = String.valueOf(a).length();
String sqr = String.valueOf(a * a);
if(sqr.length() == 1) return a == 1;
int idx = sqr.length() - d;
long x = Long.valueOf(sqr.substring(0, idx));
long y = Long.valueOf(sqr.substring(idx));
return x + y == a;
}
}```

Note: This problem (Modified Kaprekar Numbers) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.