-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPerfectSquare.java
52 lines (42 loc) · 1.92 KB
/
PerfectSquare.java
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
44
45
46
47
48
49
50
51
52
public class PerfectSquare {
// Write a function nextPerfectSquare that returns the first perfect square that is greater than
// it's integer argument. A perfect square is an integer that is equal to some integer squared.
//
// For example 16 is a perfect square because 16 = 4*4. However 15 is not a perfect square because
// there is no integer n such that 15 = n*n.
//
// The signature of the function is
// int isPerfectSquare(int n)
// Examples
// -------------------------|--------------------------------------------------------------
// | n | next perfect square |
// |-------------------------|--------------------------------------------------------------|
// | 6 | 9 |
// |-------------------------|--------------------------------------------------------------|
// | 36 | 49 |
// |-------------------------|--------------------------------------------------------------|
// | 0 | 1 |
// |-------------------------|--------------------------------------------------------------|
// | -5 | 0 |
// -------------------------|--------------------------------------------------------------
static int isPerfectSquare(int n) {
int current = n + 1;
while (true) {
for (int i=0;i<=current;i++) {
if (i*i == current) {
return current;
}
}
current++;
}
}
static void perfectSquareTest() {
System.out.println(isPerfectSquare(6));
System.out.println(isPerfectSquare(36));
System.out.println(isPerfectSquare(0));
System.out.println(isPerfectSquare(-5));
}
public static void main(String[] args) {
perfectSquareTest();
}
}