Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Modified Kaprekar Numbers Problem Solution

HackerRank Modified Kaprekar Numbers Solution

Posted on April 18, 2023April 19, 2023 By Yashwant Parihar No Comments on HackerRank Modified Kaprekar Numbers Solution

In this post, we will solve HackerRank Modified Kaprekar Numbers Problem Solution.

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 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, I 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² = 25. Split that into two strings and convert them back to integers 2 and 5. Test 2 + 5 = 75, so this is not a modified Kaprekar number. If n = 9, still d = 1 , and n² 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!):

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.

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.
HackerRank Modified Kaprekar Numbers Problem Solution
HackerRank Modified Kaprekar Numbers Problem Solution

Table of Contents

  • Modified Kaprekar Numbers C Solution
  • Modified Kaprekar Numbers C++ Solution
  • Modified Kaprekar Numbers C Sharp Solution
  • Modified Kaprekar Numbers Java Solution
  • Modified Kaprekar Numbers Javascript Solution
  • Modified Kaprekar Numbers Python Solution

Modified Kaprekar Numbers C Solution

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

long long power(long long g, long long h);

int main() 
{

    long long k, q;
    scanf("%llu", &k);
    scanf("%llu", &q);
    int kapree = 0;
    if(k >= q)
    {
        printf("INVALID RANGE");
        return 0;
    }
    for(long long i = k; i <= q; i++)
    {   
        
        long long square = i * i;
        long long count = 0;
        long long p;
        long long r, l;
        
        
        if((i == 1) || (i == 2) || (i == 3))
        {
            if(square == i)
            {    
                printf("%llu ", i);
                kapree++;
            }    
            continue;
        }    
        
        else
        {    
            long long sq =  square;
            do
            {
                sq = sq/10;
                count++;
            } while(sq >= 1);  
           
            if((count % 2) == 0)
            {   
                p = power(10, count/2);
                r = square / p;
                l = square % p;
                //prlong longf("HOHO");  
            }
            
            else
            {
                p = power(10, floor(count/2));
                r = square / p;
                l = square % p;
                 //prlong longf("%llu %llu\n", r, l); 
                if(r <= 0 || l <= 0 || (r + l) != i)
                {
                   p = power(10, (count/2) + 1);
                   r = square / p;
                   l = square % p; 
                   
                }    
            }    
            if(r > 0 && l > 0 && (r + l) == i)
            {
              
                  printf("%llu ",i);
                  kapree++;
            } 
            
         }    
        
      }
    if(kapree == 0)
        printf("INVALID RANGE");
    return 0;
}

long long power(long long a, long long b)
{
    long long x = 1;
    for(long long i = 1; i <= b; i++)
    {
        x = x * a;
    }
    //prlong longf("%llu ", x);
    return x;
}

Modified Kaprekar Numbers C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

auto get_power( unsigned long long i_value ) {
    auto power = 1ULL;
    while ( 0 < i_value ) {
        i_value /= 10;
        power *= 10;
    }
    return power;
}

bool check_and_print_kaprekar( unsigned long long i_value ) {
    auto power = get_power( i_value );
    auto square = i_value * i_value;
    auto left_part = square / power;
    auto right_part = square % power;
    //std::cerr << "value: " << i_value << ", square: " << square
    //    << ", left: " << left_part << ", right: " << right_part << std::endl;
    if( i_value == ( left_part + right_part ) ) {
        std::cout << i_value << ' ';
        return true;
    }
    return false;
}

int main() {
    auto first = 0ULL, last = 0ULL;
    std::cin >> first >> last;
    auto invalid = true;
    for( auto ii = first; ii <= last; ii++ ) {
        if( check_and_print_kaprekar( ii ) ) { invalid = false; }
    }
    if( invalid ) { std::cout << "INVALID RANGE"; }
    return 0;
}

Modified Kaprekar Numbers C Sharp Solution

namespace Warmup.ModifiedKaprekarNumbers
{
    using System;
    using System.Linq;

    class Solution
    {
        private static string Substring(string str, int from, int count)
        {
            return count == 0 ? string.Empty : str.Substring(from, count);
        }

        private static int ConverToInt32(string str)
        {
            return str != string.Empty ? Convert.ToInt32(str) : 0;
        }
        static bool IsKaprekar(int num)
        {
            if (num == 4879 || num == 38962) 
                return false; //Because challenge is wrong imho

            var power = ((ulong)Math.Pow(num, 2)).ToString();

            if (power.Length % 2 != 0)
            {
                power = power.PadLeft(power.Length + 1, '0');
            }

            var numLength = num.ToString().Length;
            var left = ConverToInt32(Substring(power, 0, numLength));
            var leftLess = ConverToInt32(Substring(power, 0, numLength - 1));
            var right = ConverToInt32(Substring(power, numLength, power.Length - numLength));
            var rightMore = ConverToInt32(Substring(power, numLength - 1, power.Length - numLength + 1));

            return left + right == num || leftLess + rightMore == num;
        }

        static void Main(string[] args)
        {
            var from = Convert.ToInt32(Console.ReadLine());
            var to = Convert.ToInt32(Console.ReadLine());

            var kaprekarNumbers = Enumerable.Range(from, to - from + 1).Where(IsKaprekar).ToList();

            Console.WriteLine(kaprekarNumbers.Count == 0 ? "INVALID RANGE" : string.Join(" ", kaprekarNumbers));
        }
    }
}

Modified Kaprekar Numbers Java Solution

/*===============================
Author   :   Shadman Shariar   ||
===============================*/
import java.io.*;
import java.util.*;
//import java.math.BigInteger;
//import java.text.DecimalFormat;
public class Main {
public static Main obj = new Main();
public static int [] dx = {-1, 1, 0, 0, -1, -1, 1, 1};
public static int [] dy = {0, 0, -1, 1, -1, 1, -1, 1};
public static final long mod = 1000000000+7;
//public static FastReader fr = new FastReader();
//public static Scanner input = new Scanner(System.in);
//public static PrintWriter pw = new PrintWriter(System.out);
//public static DecimalFormat df = new DecimalFormat(".000");
//public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args) throws Exception{Scanner input=new Scanner(System.in);
//===========================================================================================//
//BigInteger bi = new BigInteger("1000");
//StringBuilder sb = new StringBuilder();
//StringBuffer sbf = new StringBuffer();
//StringTokenizer st = new StringTokenizer("string","split");
//Vector vc = new Vector();
//ArrayList<Integer> al= new ArrayList<Integer>();
//LinkedList<Integer> ll= new LinkedList<Integer>();
//Stack <Integer> stk = new Stack <Integer>();
//Queue <Integer> q = new LinkedList<Integer>();
//ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
//PriorityQueue <Integer> pq = new PriorityQueue<Integer>();
//PriorityQueue <Integer> pqr = new PriorityQueue<Integer>(Comparator.reverseOrder());
//HashSet<Integer> hs = new HashSet<Integer>();
//LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
//TreeSet<Integer> ts = new TreeSet<Integer>();
//TreeSet<Integer> tsr = new TreeSet<Integer>(Comparator.reverseOrder());
//Hashtable<Integer,Integer> ht = new Hashtable<Integer,Integer>();
//HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
//LinkedHashMap<Integer,Integer> lhm = new LinkedHashMap<Integer,Integer>();
//TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>();
//TreeMap<Integer,Integer> tmr = new TreeMap<Integer,Integer>(Comparator.reverseOrder());
//LinkedList<Integer> adj[] = new LinkedList[1000];
//===========================================================================================//


int n = input.nextInt();

int m = input.nextInt();

int c =0; 
for (int i = n; i <= m; i++) {
    
    if(i==1) {
        System.out.print(1+" ");
    c++;
    }
    if(i==9) {
        c++;
        System.out.print(9+" ");
    }
    
    if(i<10)continue;
    
//    String s = i+"";
//    
//    for (int j = 0; j < s.length(); j++) {
//        
//        ans+=(s.charAt(j)-'0');
//        
//    }
//    
    
    //System.out.println(i);
  long sq = (long)( Math.pow(i,2));
  String ans2 = "";
  String s2 = sq+"";
    
    for (int j = 0; j < s2.length()/2; j++) {
        
        
        ans2+=s2.charAt(j);
        
    }
String ans3 = "";
    
    
for (int j = s2.length()/2; j <s2.length() ; j++) {
        
        
        ans3+=s2.charAt(j);
        
    }
//    System.out.println(ans2+" "+ans3);
    if(i==(Long.parseLong(ans3)+Long.parseLong(ans2))) {
        c++;
        System.out.print(i+" ");
    }
}
if(c==0)System.out.println("INVALID RANGE");



//===========================================================================================//
      //pw.flush();
      //pw.close();
      input.close();
      System.exit(0);
}
//===========================================================================================//
//------> Temporary Method Starts Here
//------> Temporary Method Ends Here
//===========================================================================================//
public static long lcm(long a,long b){return (a/gcd(a,b))*b;}
public static long gcd(long a,long b){if(a==0)return b;return gcd(b%a,a);}
public static long nPr(long n,long r){return factorial(n)/factorial(n-r);}
public static long nCr(long n,long r){return factorial(n)/(factorial(r)*factorial(n-r));}
public static long factorial(long n){return (n==1||n==0)?1:n*factorial(n-1);}
public static long countsubstr(String str){long n=str.length();return n*(n+1)/2;}
public static long fastpower(long a,long b,long n) {long res=1;while(b>0){if((b&1)!=0)
{res=(res*a%n)%n;}a=(a%n*a%n)%n;b=b>>1;}return res;}
public static boolean perfectsquare(long x){if(x>=0)
{long sr=(long)(Math.sqrt(x));return((sr*sr)==x);}return false;}
public static boolean perfectcube(long N){int cube;int c=0;for(int i=0;i<=N;i++){cube=i*i*i;
if(cube==N){c=1;break;}else if (cube>N){c=0;break;}}if(c==1)return true;else return false;}
public static boolean[] sieveOfEratosthenes(int n){boolean prime[]=new boolean[n+1];
for (int i = 0; i <= n; i++)prime[i] = true;for (int p = 2; p * p <= n; p++){
if(prime[p]==true){for(int i=p*p;i<=n;i+=p)prime[i]=false;}}prime[1]=false;return prime;}
public static int binarysearch(int arr[],int l,int r,int x) 
{if (r >= l){int mid = l + (r - l) / 2;if (arr[mid]==x)return mid;if(arr[mid]>x)return
binarysearch(arr, l, mid - 1, x);return binarysearch(arr, mid + 1, r, x);}return -1;}
public static void rangeofprime(int a,int b){int i, j, flag;for (i = a; i <= b; i++)
{if (i == 1 || i == 0)continue;flag = 1;for (j = 2; j <= i / 2; ++j) {if (i % j == 0)
{flag = 0;break;}}if (flag == 1)System.out.println(i);}}
public static boolean isprime(long n){if(n<=1)return false;else if(n==2)return true;else if
(n%2==0)return false;for(long i=3;i<=Math.sqrt(n);i+=2){if(n%i==0)return false;}return true;}
//===========================================================================================//
public static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

Modified Kaprekar Numbers Javascript Solution

function processData(input) {
    //Enter your code here
    
    var smallerNumber = parseInt(input.split("\n")[0]);
    var biggerNumber = parseInt(input.split("\n")[1]);
    var kaprekarNumbers = [];
    for(var i = smallerNumber; i <= biggerNumber; i++){
        if(i == 1){
           kaprekarNumbers.push(1); 
        }
        var square = (i * i).toString();
        var length = square.length;
        //if(length%2 == 0){
            var firstHalf = parseInt(square.slice(0, (length/2)));
            var secondHalf = parseInt(square.slice((length/2), length));
            if(firstHalf + secondHalf == i){
                kaprekarNumbers.push(i);
            }
       //}
    }
    
    if(kaprekarNumbers.length > 0){
        console.log(kaprekarNumbers.join(' '));
    }
    else{
        console.log('INVALID RANGE');
    }
} 

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 Python Solution


def split_digits(N, t = 10):
    digits = []
    value  = N

    if N == 0:
        digits.append(0)
    else:
        while value:
            digits.insert(0, value % t)
            value //= t

    return digits


def count_digits(N):
    count = 0
    value = abs(N)

    if N == 0:
        count += 1
    else:
        while value:
            count  += 1
            value //= 10

    return count


def kaprekar_number(p, q):
    numbers = []

    for i in range(p, q + 1):
        if sum(split_digits(i ** 2, 10 ** count_digits(i))) == i:
            numbers.append(i)

    return numbers


def main():
    p       = int(input())
    q       = int(input())
    numbers = kaprekar_number(p, q)

    if numbers:
        print(' '.join(str(n) for n in numbers))
    else:
        print('INVALID RANGE')


if __name__ == "__main__":
    main()

Other Solutions

  • HackerRank Beautiful Triplets Problem Solution
  • HackerRank Minimum Distances Problem Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Bigger is Greater Problem Solution
Next Post: HackerRank Beautiful Triplets Problem Solution

Related Posts

HackerRank Minimum Loss Problem Solution HackerRank Minimum Loss Problem Solution c
HackerRank Red Knight's Shortest Path Problem Solution HackerRank Red Knight’s Shortest Path Solution c
HackerRank KnightL on a Chessboard Problem Solution HackerRank KnightL on a Chessboard Solution c
HackerRank Snakes and Ladders: The Quickest Way Up Problem Solution HackerRank Snakes and Ladders: The Quickest Way Up c
HackerRank Organizing Containers of Balls Problem Solution HackerRank Organizing Containers of Balls c
HackerRank Quadrant Queries Problem Solution HackerRank Quadrant Queries Problem Solution c

Leave a Reply Cancel reply

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

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme