Skip to content

Instantly share code, notes, and snippets.

@DoNotLickToaster
Last active December 11, 2016 04:44
Show Gist options
  • Save DoNotLickToaster/15ff71f86b3a229abcebecc39412be41 to your computer and use it in GitHub Desktop.
Save DoNotLickToaster/15ff71f86b3a229abcebecc39412be41 to your computer and use it in GitHub Desktop.
Takes the input of two integers and outputs all the Kaprekar numbers in that range
/*
* twitter.com/acidflip
* KaprekarNumbers
* December 10th, 2016
*
* Takes the input of two integers and outputs all the Kaprekar numbers in that range
*
* 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^2 = 2025 and 20+25 = 45. The Kaprekar numbers are named after D. R. Kaprekar.
*/
import java.util.Scanner;
public class KaprekarNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first integer");
int firstNum = Math.abs(keyboard.nextInt());
System.out.println("Enter the second integer");
int secondNum = Math.abs(keyboard.nextInt());
System.out.println("\nThe Kaprekar numbers between " + firstNum + " and " + secondNum + " are...");
for (int i = firstNum; i < secondNum; i++) {
int resultNum = kapNum(i);
if (resultNum != -1) {
System.out.println(resultNum);
}
}
}
public static int kapNum(int number) {
int square = number * number;
String result = Integer.toString(square);
int length = result.length();
if (length == 1) {
return -1;
} else {
for (int index = 1; index < length; index++) {
int num1 = Integer.parseInt(result.substring(0, index));
int num2 = Integer.parseInt(result.substring(index, length));
if (num1 == 0 || num2 == 0) {
continue;
}
if (num1 + num2 == number) {
return number;
}
}
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment