1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// Without using Inbuilt Methods of Java class PerfectSquare{ public static void main(String args[]){ int a=Integer.parseInt(args[0]); double temp = a; int count[] = new int[4]; count[0]=count[1]=count[2]=count[3]=0; while (temp>1){ if(temp%2==0) { count[0]++; temp /=2; } if(temp%3==0) { count[1]++; temp /=3; } if(temp%5==0) { count[2]++; temp /=5; } if(temp%7==0) { count[3]++; temp /=7; } } int y = 1; if(count[0]>0 && count[0]%2!=0) y=0; if(count[1]>0 && count[1]%2!=0) y=0; if(count[2]>0 && count[2]%2!=0) y=0; if(count[3]>0 && count[3]%2!=0) y=0; if(y==1) System.out.println("yes it is square"); else System.out.println("no it is not square"); } } |
We can use Math class sqrt
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// using built in functions import java.math.*; class PerfectSquare{ public static void main(String args[]){ int a=Integer.parseInt(args[0]); int sqrt = (int) Math.sqrt(a); if(sqrt*sqrt == a) System.out.println("yes it is perfect square"); else System.out.println("no it is not perfect square"); } } |
Discussion
Give Input as command line arguments : java PerfectSquare 36