Modified Kaprekar Numbers HackerRank Solution in C, C++, Java, Python

A 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 and d with digits. We square n to arrive at a number that is either 2*d digits long or (2*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 n^2=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 n^2=81. This gives us , 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.

Modified Kaprekar Numbers HackerRank 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 HackerRank Solution in C++

#include <functional>
#include <algorithm>
#include <iostream>
#include <climits>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>

using namespace std;

typedef long long        LL;
typedef pair<int, int>   pii;
typedef pair<int, pii>   piii;
typedef vector<int>      vi;
typedef vector<pii>      vii;
typedef vector<piii>     viii;

#ifdef _WIN32
#define getchar_unlocked getchar
#endif
inline void inpint( int &n ) {
  n=0; register int ch = getchar_unlocked(); bool sign = 0;
  while(ch < 48 || ch > 57) { if(ch == '-') sign = 1; ch = getchar_unlocked(); }
  while(ch >= 48 && ch <= 57) { n = (n << 3) + (n << 1) + ch - 48, ch = getchar_unlocked(); }
  if(sign) n = -n;
}

inline int sqr(int x){return x * x;}
inline int cube(int x){return x * x * x;}
inline LL sqrLL(LL x){return x * x;}
inline LL cubeLL(LL x){return x * x * x;}

const LL LLINF      = 9223372036854775807LL;
const LL LLINF17    = 100000000000000000LL;
const int INF       = 2147483647;
const int INF9      = 1000000000;
const int MOD       = 1000000007;
const double eps    = 1e-7;
const double PI     = acos(-1.0);

#define FOR(a,b,c)   for (int (a)=(b); (a)<(c); (a)++)
#define FORN(a,b,c)  for (int (a)=(b); (a)<=(c); (a)++)
#define FORD(a,b,c)  for (int (a)=(b); (a)>=(c); (a)--)
#define REP(i,n)     FOR(i,0,n)
#define REPN(i,n)    FORN(i,1,n)
#define REPD(i,n)    FORD(i,n,1)

#define RESET(a,b)   memset(a,b,sizeof(a)) 
#define SYNC         ios_base::sync_with_stdio(0);
#define SIZE(a)      (int)(a.size())
#define MIN(a,b)     (a) = min((a),(b))
#define MAX(a,b)     (a) = max((a),(b))
#define ALL(a)       a.begin(),a.end()
#define RALL(a)      a.rbegin(),a.rend()
#define SIZE(a)      (int)(a.size())
#define LEN(a)       (int)(a.length())

#define fi           first
#define se           second
#define pb           push_back
#define mp           make_pair

int dr[] = {1,0,-1,0,-1,1,1,-1};
int dc[] = {0,-1,0,1,1,1,-1,-1};
int p, q;
inline int go(int z) {
  int ans = 0;
  while (z) {
    ans++;
    z /= 10;
  } return ans;
}
int main(){
  int ans = 0;
  cin >> p >> q;
  bool fir = true;
  for (int z = p; z <= q; z++) {
    int cnt = go(z);

    LL lol = sqrLL((LL)(z));

    vi v;
    while (lol) {
      v.pb(lol % 10);
      lol /= 10;
    }

    vi v1, v2;
    int half = cnt;
    int val1 = 0, val2 = 0;
    REP(i,half) {
      v1.pb(v[i]);
    }
    FOR(i,half,SIZE(v)) {
      v2.pb(v[i]);
    }

    while(SIZE(v1)) {
      val1 = val1 * 10 + v1.back();
      v1.pop_back();
    }

    while(SIZE(v2)) {
      val2 = val2 * 10 + v2.back();
      v2.pop_back();
    }

    if (val1 + val2 == z) {
      // cout << val1 << " " << val2 << endl;
      if (!fir) printf(" ");
      else fir = false;
      printf("%d",z);
      ans++;
    }
  }
  if(!ans) puts("INVALID RANGE");
  puts("");

  return 0;
}

 

Modified Kaprekar Numbers HackerRank 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;
    }
}

 

Modified Kaprekar Numbers HackerRank 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 HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args)
        {
            int p = Int32.Parse(Console.ReadLine());
            int q = Int32.Parse(Console.ReadLine());
            bool Found = false;
            for(int i = p; i <= q; i ++)
            {
                if(kaprekar(i))
                    Found = true;
            }
            if (!Found)
                Console.WriteLine("INVALID RANGE");
        }
        static bool kaprekar(Int64 n)
        {
            if (n == 1)
            {
                Console.Write("1 ");
                return true;
            }
            Int64 res = n * n;
            string temp = res.ToString();
            if (temp.Length >= 2)
            {
                Int64 n1 = Int64.Parse(temp.Substring(0, temp.Length / 2));
                Int64 n2 = Int64.Parse(temp.Substring(temp.Length / 2));
                if (n1 + n2 == n && n1 != 0 && n2 != 0)
                {
                    Console.Write(n + " ");
                    return true;
                }
            }
            return false;
        }
}

 

Attempt Modified Kaprekar Numbers HackerRank Challenge

Link – https://www.hackerrank.com/challenges/kaprekar-numbers/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/beautiful-triplets-hackerrank-solution/

 

Leave a Comment