HackerRank Modified Kaprekar Numbers Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Modified Kaprekar Numbers Solution. This problem is a part of the HackerRank Algorithms Series.

Ezoicreport this adHackerRank Modified Kaprekar Numbers Solution
HackerRank Modified Kaprekar Numbers Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Modified Kaprekar Numbers Solution

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

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.

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);
            count++;
        }
    }
    if (count == 0)
        printf("INVALID RANGE");
    printf("\n");
    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(" ");
				}
				System.out.print(i);
				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;
			d++;
			div *= 10;
		}
		
		long sq = n * n;
		long left = sq / div;
		long right = sq % div;
		
		//System.out.println(n + " " + left + " " + right);
		
		return left + right == n;
	}
}
Ezoicreport this ad

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"
else:
    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 {
        console.log(Kaprekars);
    }
} 
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;
} 

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

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

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

var
   a,b,i,k:longint;
   bol:boolean;
function Kaprekar(n:int64):boolean;
var
   izq,der,diez:int64;
   d:integer;
   cad:string;
begin
    izq:=n*n;
    str(izq,cad);
    d:=(length(cad)+1) div 2;
    der:=0;
    diez:=1;
    while d>0 do
    begin
       der:=der+diez*(izq mod 10);
       izq:=izq div 10;
       diez:=diez*10;
       d:=d-1;
    end;
    if izq+der=n then
       Kaprekar:=true
    else
    Kaprekar:=false;
end;
begin
   read(a,b);
   bol:=false;
   for i:=a to b do
      if Kaprekar(i) then
      begin
         k:=k+1;
         write(i,' ');
         bol:=true;
      end;
  if not bol then
     writeln('INVALID RANGE');

end.

Disclaimer: This problem (Modified Kaprekar Numbers) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Service Lane Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad