Programming Examples

Java program to input a number and check whether it is a Kaprekar number or not


Write a program to input a number and check whether it is a Kaprekar number or not. Take a positive whole number n that has d number of digits. Take the square n and separate the result into two pieces: a right-hand piece that has d digits and a left-hand piece that has either d or d-1 digits. Add these two pieces together. If the result is n, then n is a Kaprekar number.

Examples are 9 (92 = 81, 8 + 1 = 9), 45 (452 = 2025, 20 + 25 = 45), and 297 (2972 = 88209, 88 + 209 = 297).

Solution

import java.util.*;
class Kaprekar
{
	public static void main(String arr[])
	{
		Scanner sc=new Scanner(System.in);
		int i,d=0,a,s=0,f,l;
		System.out.println("Enter an integer:");
		a=sc.nextInt();
		for(i=a;i>0;i=i/10)
		{
			d++;
		}
		s=a*a;
		f=s/(int)Math.pow(10,d);
		l=s%(int)Math.pow(10,d);
		if(f+l==a)
		System.out.println("Kaprekar Number");
		else
		System.out.println("Not a Kaprekar Number");
	}
}
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz