Friday, June 28, 2019

Kaprekar Number | Programming | Eclipse JAVA | Follow on Youtube for more

Code:
import java.util.*;
public class kaprekar_number
{
static int check(int square,int n)
{
String s = Integer.toString(square);
int l = s.length();
if(l%2==0) // when square has even digits
{
String s1 = s.substring(0,l/2);//20
int n1 = Integer.parseInt(s1);
String s2 =s.substring(l/2,l); //25
int n2 = Integer.parseInt(s2);
System.out.println(s1+"  "+s2);
if((n1+n2)==n&& n1>0 &&n2>0)
return 1;
}
else // When the square has odd digits
{
String s1 = s.substring(0,l/2+1);
int n1 = Integer.parseInt(s1);
String s2 =s.substring(l/2+1,l);
int n2 = Integer.parseInt(s2);
System.out.println(s1+"  "+s2);
if((n1+n2)==n && n1>0 &&n2>0)
return 1;
String s3 = s.substring(0,l/2);
int n3 = Integer.parseInt(s3);
String s4 =s.substring(l/2,l);
int n4 = Integer.parseInt(s4);
System.out.println(s3+"  "+s4);
if(((n3+n4)==n)&& n3>0 &&n4>0)
return 1;
}

return 0;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked");
int n = sc.nextInt();
int square = n*n;
System.out.println(square);
int result  = check(square,n);
if(result ==1)
System.out.println(n+" is a kaprekar number");
else
System.out.println(n+" is not a kaprekar number");
sc.close();
}
}


/*
Input :  n = 45
Output : Yes
Explanation : 45^2 = 2025 and 20 + 25 is 45

Input : n = 13
Output : No
Explanation : 13^2 = 169. Neither 16 + 9 nor 1 + 69 is equal to 13

Input  : n = 297
Output : Yes
Explanation:  297^2 = 88209 and 88 + 209 is 297 and 882+09 = 891

Input  : n = 10
Output : No
Explanation:  10^2 = 100. It is not a Kaprekar number even if
sum of 10 + 0 is 10. This is because of the condition that
none of the parts should have value 0.
 */

No comments:

Post a Comment

ICSE COMPUTER SCIENCE SPECIMEN PAPER | QUESTION 7 | PLEASE DO WATCH THE VIDEO

  import  java.util.*; class icse_specimen_1 {     public static void main(String[] args)     {         Scanner sc1 = new Scanner(System.in)...