forked from anishrauniyar/EasySolutionMUM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfectSquare.java
More file actions
43 lines (35 loc) · 949 Bytes
/
PerfectSquare.java
File metadata and controls
43 lines (35 loc) · 949 Bytes
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
34
35
36
37
38
39
40
41
42
43
import java.util.Scanner;
// example: next perfect square of 5 is 9
public class PerfectSquare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
int n = 0;
try {
n = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("This is not a number");
n = 0;
}
if (n == 0) {
System.out.println("The next perfect square is: 1");
} else if (n < 0) {
System.out.println("The next perfect square is: 0");
} else if (n > 0) {
int nextPerfect = isPerfectSquare(n);
System.out.println("The next perfect square is: " + nextPerfect);
}
sc.close();
}
private static int isPerfectSquare(int n) {
// TODO Auto-generated method stub
double perf = 0;
for (int i = n+1; ;i++) {
perf = Math.sqrt(i);
if (perf % 1 == 0) {
break;
}
}
return (int) (perf*perf);
}
}