KaprekarNumbers
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of p: ");
int p = scanner.nextInt();
System.out.print("Enter the value of q (where p < q): ");
int q = scanner.nextInt();
scanner.close();
if (p >= q)
{
System.out.println("Invalid input. Please make sure p < q.");
return;
}
int count = countKaprekarNumbers(p, q);
System.out.println("Number of Kaprekar numbers between " + p + " and " + q + ": " + count);
}
private static int countKaprekarNumbers(int p, int q)
{
int count = 0;
for (int num = p; num <= q; num++)
{
if (isKaprekarNumber(num))
{
System.out.println(num+" ");
count++;
}
}
return count;
}
private static boolean isKaprekarNumber(int num)
{
long square = (long) num * num;
String squareStr = String.valueOf(square);
for (int i = 1; i < squareStr.length(); i++)
{
String leftStr = squareStr.substring(0, i);
String rightStr = squareStr.substring(i);
int left = (leftStr.isEmpty()) ? 0 : Integer.parseInt(leftStr);
int right = (rightStr.isEmpty()) ? 0 : Integer.parseInt(rightStr);
if (left + right == num && left > 0 && right > 0)
{
return true;
}
}
return false;
}
}
No comments:
Post a Comment