Modified Kaprekar Numbers Hackerrank problem solution

Modified Kaprekar Numbers Hackerrank

A modified Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces – a right hand piece r with d digits and a left hand piece l that contains the remaining d or d-1 digits, the sum of the pieces is equal to the original number (i.e. l + r = 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.

The Task
You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and display them all.

Input Format

There will be two lines of input: p, lowest value q, highest value

Constraints:
0solution

The steps are fairly direct.
(1) Compute the square of the original number.
(2) Split it into two parts as described.
(3) Check if they add up and equal the original number.
(4) The number 1 might need to be handled separately.
The solution code from the creator of this challenge is also provided below.

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

int main() {
    int p,q,c=0;
    scanf("%d",&p);
    scanf("%d",&q);
 int count = 0;
    for (long long i = p; i <= q; i++) {
        long long square = i * i;
        long long square_copy = square;
        int digCount = 0;
        while (square_copy) {
            square_copy /= 10;
            digCount++;
        }
        digCount += digCount%2;

        long long power = 10;
        for (long long k = 1; k < digCount/2; k++) {
            power *= 10;
        }
        long long r = square % power;
        long long l = square / power;
        if (r + l == i) {
          printf("%lld ", i); 
          count++;
        }

    }

    if (count == 0) {
        printf("INVALID RANGE");
    }
    return 0;
}
def kaprekar(i):
    if i == 1:
        return True
    s = i ** 2
    s = str(s)
    length = len(s)
    if len(s) <= 1:
        return False
    temp = int(s[0:length/2]) + int(s[length/2:])
    if temp == i:
        return True
    else:
        return False
a = input()
b = input()
l = []
for i in range(a, b + 1):
    if kaprekar(i):
        l.append(i)
if not l:
    print "INVALID RANGE"
else:
    print " ".join(map(str, l))

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.