Given an integer n, return the first n Kaprekar numbers. A Kaprekar number is a positive integer k such that when k² is split into two parts, where the right part contains exactly as many digits as k and the left part contains the remaining digits, the sum of these two parts equals k.
For example: 297 is a Kaprekar number because 2972= 88209 and 88 + 209 = 297.
Examples:
Input: n = 3
Output: [1, 9, 45]
Explanation: These are the first three Kaprekar numbers.
1 is a Kaprekar number because 1² = 1 and 0 + 1= 1.
9 is a Kaprekar number because 9² = 81 and 8 + 1 = 9.
45 is a Kaprekar number because 45² = 2025 and 20 + 25 = 45.Input: n = 5
Output: [1, 9, 45, 55, 99]
Explanation: These are the first five Kaprekar numbers.
55 is a kaprekar number because 552 = 3025 and 30 + 25 = 55.
99 is a kaprekar number because 992 = 9801 and 98 + 01 = 99.
Table of Content
Check Every Number Using String Splitting - O(m × d) Time and O(d) Space
The idea is to generate numbers one by one. Convert the square of each number into a string, split it into left and right parts, and check whether their sum equals the original number. Store every Kaprekar number in res until it contains n numbers.
Working of Approach:
- Start checking numbers one by one from 1 until the first n Kaprekar numbers are found.
- For each number, compute its square and convert it into a string.
- Split the square into two parts so that the right part has the same number of digits as the original number.
- Convert both parts back to integers and check whether their sum equals the original number.
- If it is a Kaprekar number, add it to the result and continue until n numbers are collected.
#include <bits/stdc++.h>
using namespace std;
bool isKaprekar(int x)
{
if (x == 1)
return true;
long long sq = 1LL * x * x;
string s = to_string(sq);
int digits = to_string(x).size();
int split = s.size() - digits;
string left = (split > 0) ? s.substr(0, split) : "";
string right = s.substr(split);
long long l = left.empty() ? 0 : stoll(left);
long long r = stoll(right);
if (r == 0)
return false;
return (l + r == x);
}
vector<int> kaprekarNumbers(int n)
{
vector<int> res;
int num = 1;
while ((int)res.size() < n)
{
if (isKaprekar(num))
res.push_back(num);
num++;
}
return res;
}
int main()
{
int n = 5;
vector<int> res = kaprekarNumbers(n);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i + 1 < res.size())
cout << ", ";
}
cout << "]" << endl;
return 0;
}
import java.util.*;
public class GFG {
static boolean isKaprekar(int x)
{
if (x == 1)
return true;
long sq = 1L * x * x;
String s = Long.toString(sq);
int digits = Integer.toString(x).length();
int split = s.length() - digits;
String left
= (split > 0) ? s.substring(0, split) : "";
String right = s.substring(split);
long l = left.isEmpty() ? 0 : Long.parseLong(left);
long r = Long.parseLong(right);
if (r == 0)
return false;
return (l + r == x);
}
static ArrayList<Integer> kaprekarNumbers(int n)
{
ArrayList<Integer> res = new ArrayList<>();
int num = 1;
while (res.size() < n) {
if (isKaprekar(num))
res.add(num);
num++;
}
return res;
}
public static void main(String[] args)
{
int n = 5;
ArrayList<Integer> res = kaprekarNumbers(n);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i + 1 < res.size())
System.out.print(", ");
}
System.out.println("]");
}
}
def isKaprekar(x):
if x == 1:
return True
sq = x * x
s = str(sq)
digits = len(str(x))
split = len(s) - digits
left = s[:split] if split > 0 else ""
right = s[split:]
l = int(left) if left else 0
r = int(right)
if r == 0:
return False
return l + r == x
def kaprekarNumbers(n):
res = []
num = 1
while len(res) < n:
if isKaprekar(num):
res.append(num)
num += 1
return res
if __name__ == "__main__":
n = 5
res = kaprekarNumbers(n)
print(res)
using System;
using System.Collections.Generic;
class GFG {
static bool IsKaprekar(int x)
{
if (x == 1)
return true;
long sq = 1L * x * x;
string s = sq.ToString();
int digits = x.ToString().Length;
int split = s.Length - digits;
string left
= (split > 0) ? s.Substring(0, split) : "";
string right = s.Substring(split);
long l = left.Length == 0 ? 0 : long.Parse(left);
long r = long.Parse(right);
if (r == 0)
return false;
return (l + r == x);
}
static List<int> kaprekarNumbers(int n)
{
List<int> res = new List<int>();
int num = 1;
while (res.Count < n) {
if (IsKaprekar(num))
res.Add(num);
num++;
}
return res;
}
static void Main()
{
int n = 5;
List<int> res = kaprekarNumbers(n);
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i + 1 < res.Count)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
function isKaprekar(x)
{
if (x === 1)
return true;
let sq = x * x;
let s = sq.toString();
let digits = x.toString().length;
let split = s.length - digits;
let left = (split > 0) ? s.substring(0, split) : "";
let right = s.substring(split);
let l = left === "" ? 0 : parseInt(left);
let r = parseInt(right);
if (r === 0)
return false;
return (l + r === x);
}
function kaprekarNumbers(n)
{
let res = [];
let num = 1;
while (res.length < n) {
if (isKaprekar(num))
res.push(num);
num++;
}
return res;
}
// Driver Code
let n = 5;
let res = kaprekarNumbers(n);
console.log("[" + res.join(", ") + "]");
Output
[1, 9, 45, 55, 99]
Splitting Using Powers of 10 - O(m × d) Time and O(1) Space
The idea is to generate numbers one by one and check whether each is a Kaprekar number. Count the digits in the number, use 10^digits to split its square into left and right parts using division and modulo, and if their sum equals the original number, add it to res.
Working of Approach:
- Start checking numbers one by one from 1 until res contains the first n Kaprekar numbers.
- For each number, compute its square and count its digits.
- Use 10^digits to split the square into the left and right parts using division and modulo.
- If the right part is non-zero and the sum of both parts equals the original number, add it to res.
- Continue until res contains exactly n Kaprekar numbers.
#include <bits/stdc++.h>
using namespace std;
// Function to check whether x is a Kaprekar number
bool isKaprekar(long long x)
{
if (x == 1)
return true;
long long sq = x * x;
// Count digits in x
int digits = 0;
long long temp = x;
while (temp > 0)
{
digits++;
temp /= 10;
}
long long power = 1;
for (int i = 0; i < digits; i++)
power *= 10;
long long right = sq % power;
long long left = sq / power;
// Right part cannot be 0
if (right == 0)
return false;
return (left + right == x);
}
vector<int> kaprekarNumbers(int n)
{
vector<int> res;
long long num = 1;
while ((int)res.size() < n)
{
if (isKaprekar(num))
res.push_back(num);
num++;
}
return res;
}
int main()
{
int n = 5;
vector<int> res = kaprekarNumbers(n);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i + 1 < res.size())
cout << ", ";
}
cout << "]" << endl;
return 0;
}
import java.util.*;
public class GFG {
// Function to check whether x is a Kaprekar number
static boolean isKaprekar(long x)
{
if (x == 1)
return true;
long sq = x * x;
// Count digits in x
int digits = 0;
long temp = x;
while (temp > 0) {
digits++;
temp /= 10;
}
long power = 1;
for (int i = 0; i < digits; i++)
power *= 10;
long right = sq % power;
long left = sq / power;
// Right part cannot be 0
if (right == 0)
return false;
return (left + right == x);
}
static ArrayList<Integer> kaprekarNumbers(int n)
{
ArrayList<Integer> res = new ArrayList<>();
long num = 1;
while (res.size() < n) {
if (isKaprekar(num))
res.add((int)num);
num++;
}
return res;
}
public static void main(String[] args)
{
int n = 5;
ArrayList<Integer> res = kaprekarNumbers(n);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i + 1 < res.size())
System.out.print(", ");
}
System.out.println("]");
}
}
def isKaprekar(x):
if x == 1:
return True
sq = x * x
# Count digits in x
digits = 0
temp = x
while temp > 0:
digits += 1
temp //= 10
power = 10 ** digits
right = sq % power
left = sq // power
# Right part cannot be 0
if right == 0:
return False
return (left + right == x)
def kaprekarNumbers(n):
res = []
num = 1
while len(res) < n:
if isKaprekar(num):
res.append(num)
num += 1
return res
if __name__ == '__main__':
n = 5
res = kaprekarNumbers(n)
print('[', end='')
for i in range(len(res)):
print(res[i], end='' if i == len(res) - 1 else ', ')
print(']')
using System;
using System.Collections.Generic;
class GFG {
// Function to check whether x is a Kaprekar number
static bool IsKaprekar(long x)
{
if (x == 1)
return true;
long sq = x * x;
// Count digits in x
int digits = 0;
long temp = x;
while (temp > 0) {
digits++;
temp /= 10;
}
long power = 1;
for (int i = 0; i < digits; i++)
power *= 10;
long right = sq % power;
long left = sq / power;
// Right part cannot be 0
if (right == 0)
return false;
return (left + right == x);
}
static List<int> kaprekarNumbers(int n)
{
List<int> res = new List<int>();
long num = 1;
while (res.Count < n) {
if (IsKaprekar(num))
res.Add((int)num);
num++;
}
return res;
}
static void Main()
{
int n = 5;
List<int> res = kaprekarNumbers(n);
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i + 1 < res.Count)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
// Function to check whether x is a Kaprekar number
function isKaprekar(x)
{
if (x === 1)
return true;
let sq = x * x;
// Count digits in x
let digits = 0;
let temp = x;
while (temp > 0) {
digits++;
temp = Math.floor(temp / 10);
}
let power = 1;
for (let i = 0; i < digits; i++)
power *= 10;
let right = sq % power;
let left = Math.floor(sq / power);
// Right part cannot be 0
if (right === 0)
return false;
return left + right === x;
}
function kaprekarNumbers(n)
{
let res = [];
let num = 1;
while (res.length < n) {
if (isKaprekar(num))
res.push(num);
num++;
}
return res;
}
// Driver code
let n = 5;
let res = kaprekarNumbers(n);
console.log(res);
Output
[1, 9, 45, 55, 99]