Q:

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

belongs to collection: Java Basic Programs

0

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)

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to check given number Kaprekar Number or not in Java

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find cube 1 to N... >>
<< Java program to check whether a given number is ug...