HackerRank Modified Kaprekar Numbers Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Bigger is Greater Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Modified Kaprekar Numbers Solution
HackerRank Modified Kaprekar Numbers Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank 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 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.


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


It should print the list of modified Kaprekar numbers, spaceseparated 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.


  • 0 < p < q < 100000

Sample Input

STDIN Function
—– ——–
1 p = 1
100 q = 100

Sample Output

1 9 45 55 99


194555, and 99 are the modified Kaprekar Numbers in the given range.

HackerRank Modified Kaprekar Numbers Solution

Modified Kaprekar Numbers Solution in C

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

int main() {
    char *input = malloc(100);
    fgets(input, 10, stdin);
    long p = atoi(input) - 1;
    fgets(input, 10, stdin);
    long q = atoi(input);
    int count = 0;
    while (p++ < q) {
        long num = p*p;
        sprintf(input, "%ld", num);
        char tmp = input[strlen(input) / 2];
        int halflen = strlen(input) / 2;
        input[halflen] = '\0';
        long p1 = atoi(input);
        input[halflen] = tmp;
        input += halflen;
        long p2 = atoi(input);
        input -= halflen;
        if (p1 + p2 == p) {
            printf("%ld ", p);
    if (count == 0)
        printf("INVALID RANGE");
    return 0;

Modified Kaprekar Numbers Solution in Cpp

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

vector<int> pre = {1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4950, 5050, 7272, 7777, 9999, 17344, 22222, 77778, 82656, 95121, 99999};
int p, q;

int main() {
    scanf("%d%d", &p, &q);
    bool printed = false;
    for (int i = 0; i < pre.size(); i++) {
        if (pre[i] >= p && pre[i] <= q) {
            printf("%d ", pre[i]);
            printed = true;
    if (!printed) puts("INVALID RANGE");
    return 0;

Modified Kaprekar Numbers Solution in Java

import java.util.Scanner;

public class Kaprekar {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		int p = cin.nextInt();
		int q = cin.nextInt();
		boolean one = false;
		for (int i = p; i <= q; i++) {
			if (isKaprekar(i)) {
				if (one) {
					System.out.print(" ");
				one = true;
		if (!one) {
			System.out.println("INVALID RANGE");
	static boolean isKaprekar(long n) {
		long t = n;
		int d = 0; // Digits
		long div = 1;
		while (t > 0) {
			t = t / 10;
			div *= 10;
		long sq = n * n;
		long left = sq / div;
		long right = sq % div;
		//System.out.println(n + " " + left + " " + right);
		return left + right == n;

Modified Kaprekar Numbers Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT

def isGood(x):
    if x <= 3:
        return x == 1
    y = str(x*x)
    d = len(str(x))
    r = int(y[-d:])
    l = int(y[:-d])
    return l+r == x

p = int(raw_input())
q = int(raw_input())

l = []
for i in xrange(p, q+1):
    if isGood(i): l.append(i)

if len(l) == 0:
    print "INVALID RANGE"
    print ' '.join([str(x) for x in l])

Modified Kaprekar Numbers Solution using JavaScript

function processData(input) {
    //Enter your code here
    var Kaprekars = "",
        from = 0,
        end = 0;
    var ranges = input.split('\n');
    if(ranges.length>0) {
        from = +ranges[0];
    if(ranges.length>1) {
        end = +ranges[1];
    if(from < end) {
        for(var i = from; i<=end; i++) {
            if(checkKaprekar(i)) {
                Kaprekars += (Kaprekars.length !=0 ? " ": "") + i;
    if(Kaprekars.length=="") {
        console.log('INVALID RANGE');
    } else {
function checkKaprekar(input) {
    if(input>0) {
        var value = input * input + '';
        var middle = value.length - (input + '').length,
            left = +value.substring(0, middle),
            right = +value.substring(middle);

        if(left + right == input) {
            return true;
    return false;

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

process.stdin.on("end", function () {

Modified Kaprekar Numbers Solution in Scala

import scala.collection.mutable.ArrayBuffer;

object Solution {

    def main(args: Array[String]) {
        val start = Console.readInt;
        val end = Console.readInt;
        var results = new ArrayBuffer[Int]();
        for (i <- start to end) {
            val iString = (i.toLong * i.toLong).toString;
            val parts = iString.splitAt(Math.floor(iString.length / 2.0).toInt);
            if (i == parts._2.toInt + (if (parts._1.length > 0) parts._1.toInt else 0)) {
                results += i;
        println(if (results.length > 0) results.toArray.deep.mkString(" ") else "INVALID RANGE");

Modified Kaprekar Numbers Solution in Pascal

function Kaprekar(n:int64):boolean;
    d:=(length(cad)+1) div 2;
    while d>0 do
       der:=der+diez*(izq mod 10);
       izq:=izq div 10;
    if izq+der=n then
   for i:=a to b do
      if Kaprekar(i) then
         write(i,' ');
  if not bol then
     writeln('INVALID RANGE');


Disclaimer: This problem (Modified Kaprekar Numbers) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment