Home » Java programs » Java basic programs

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

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)

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.