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.

Task

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

194555, 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.

Leave a Comment

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