Java Program to Check Whether Given Number Is Kaprekar Number or Not

You are currently viewing Java Program to Check Whether Given Number Is Kaprekar Number or Not

Java program to check whether given number is Kaprekar number or not

public class KaprekarNumbers 
{
	public static void main(String[] args)
	{
		int ctr = 0;
		int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;

		for(long n = 1; n <= 1000; n++)
		{
			String St = Long.toString(n * n, base);

			for(int j = 0; j < St.length() / 2 + 1; j++)
			{
				String[] S = split_num(St, j);

				long N1 = Long.parseLong(S[0], base);
				long N2 = Long.parseLong(S[1], base);

				if(N2 == 0) break;

				if(N1 + N2 == n)
				{
					System.out.println(Long.toString(n, base) +"\t" + St + "\t  " + S[0] + " + " + S[1]);
					ctr++;
					break;
				}
			}
		}
		System.out.println(ctr + " Kaprekar numbers.");
		}

		private static String[] split_num(String str, int idx)
		{
		String[] A1 = new String[2];
		A1[0] = str.substring(0, idx);

		if(A1[0].equals("")) A1[0] = "0"; 
		A1[1] = str.substring(idx);
		return A1;
	}	
}

Output

First run:
Kaprekar number between 1 to 1000.

1	1	  0 + 1
9	81	  8 + 1
45	2025	  20 + 25
55	3025	  30 + 25
99	9801	  98 + 01
297	88209	  88 + 209
703	494209	  494 + 209
999	998001	  998 + 001
8 Kaprekar numbers.

Second run:
Kaprekar number between 1 to 100.

1	1	  0 + 1
9	81	  8 + 1
45	2025	  20 + 25
55	3025	  30 + 25
99	9801	  98 + 01
5 Kaprekar numbers.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply