In this HackerRank Modified Kaprekar Numbers problem 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 digit 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.

HackerRank Modified Kaprekar Numbers problem solution


Problem solution in Python programming.

def kaprekar(n):
    d = len(str(n))
    n_sqr = str(n*n)
    right = int(n_sqr[len(n_sqr)-d:])
    left = n_sqr[:len(n_sqr)-d]
    if left == '':
        left = 0
    left = int(left)
    #print("left:", left, "right:", right)
    return left+right == n
    
p = int(input())
q = int(input())
a = []
for i in range(p, q+1):
    if kaprekar(i):
        a.append(i)
if len(a) == 0:
    print("INVALID RANGE")
else:
    print(' '.join(str(c) for c in a))


Problem solution in Java Programming.

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;
    }
}


Problem solution in C++ programming.

#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;
}


Problem solution in C programming.

#include <stdio.h>
#include <math.h>

#define SIZE 100000

int K[SIZE];

void kaprekar() {
    long i, j, n, sq, dNo, mid, left, right, d[12];
   
    for(n = 1; n < SIZE; n++) {
        sq = n * n;
        
        dNo = 0;
        while(sq) {
            d[++dNo] = sq % 10;
            sq /= 10;
        }
        
        mid = dNo / 2;
        for(j = dNo, i = 1; i <= dNo/2; i++, j--) d[i] ^= d[j] ^= d[i] ^= d[j];
        
        for(left = j = 0, i = mid; i >= 1; i--, j++) left += d[i] * pow(10, j);
        for(right = j = 0, i = dNo; i >= mid + 1; i--, j++) right += d[i] * pow(10, j);
        
        if(left + right == n) K[n] = 1;
        else                  K[n] = 0;
    }
}

int main() {
   
    kaprekar();
    
    int i, p, q, flag;
    scanf(" %d %d", &p, &q);
    
    for(flag = 1, i = p; i <= q; i++) {
        if(K[i]) {
            printf("%d ", i);
            flag = 0;
        }
    }
    if(flag) printf("INVALID RANGE");
    
    return 0;
}


Problem solution in JavaScript programming.

function splitNum(num){
    var num = (num * num ).toString()
    var center;
    var res;
    
    if(num.length > 1){
        center = Math.floor(num.length/2)
        res = [parseInt(num.substr(0,center)),parseInt(num.substr(center,num.length))]
    }else{
        center = 0
        res = [parseInt(num),0]
    }
    return res
}


function processData(input) {
    var inputs = input.split("\n")
    var p = parseInt(inputs[0])
    var q = parseInt(inputs[1])
    var kaprekar = []
    
    for(var i = p; i <= q; i++){
        var sq = splitNum(i)
        if (sq[0]+sq[1] == i){
            kaprekar.push(i)
        }
    }
    
    if(kaprekar.length == 0){
        console.log( "INVALID RANGE")
    }else{
        console.log( kaprekar.join(" "))
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});