×

Java Programs

Java Practice

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

Here, we are going to implementing a java program that will read an integer number and check whether it is Kaprekar number or not.
Submitted by IncludeHelp, on January 02, 2018

Problem statement

Given an integer number and we have to check whether it is a Kaprekar number or not using Java program.

What is Kaprekar Number?

A Kaprekar number is a number in which the sum of digits in its square is the number itself.

Example

    
9*2= 81 (Square of 9)
8+1 = 9(Sum of digits in square)

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.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.