Skip to content

Commit cc2737e

Browse files
authored
Create YoureASquare.java
1 parent 07830ff commit cc2737e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

StreamSolutions/YoureASquare.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
A square of squares
3+
You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!
4+
However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a perfect square.
5+
Task
6+
Given an integral number, determine if it's a square number:
7+
In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.
8+
The tests will always use some integral number, so don't worry about that in dynamic typed languages.
9+
Examples
10+
-1 => false
11+
0 => true
12+
3 => false
13+
4 => true
14+
25 => true
15+
26 => false
16+
*/
17+
18+
19+
//This takes long time with large data
20+
import java.util.stream.IntStream;
21+
22+
public class Square {
23+
public static boolean isSquare(int n) {
24+
25+
if (n==0){
26+
return true;
27+
}
28+
29+
return IntStream.rangeClosed(1, n)
30+
.filter(x -> x * x == n)
31+
.findFirst()
32+
.isPresent();
33+
}
34+
}
35+
36+
//Use this instead:
37+
38+
public class Square {
39+
public static boolean isSquare(int n) {
40+
41+
if (n < 0) {
42+
return false;
43+
}
44+
45+
int sqrt = (int) Math.sqrt(n);
46+
return sqrt * sqrt == n;
47+
}
48+
}

0 commit comments

Comments
 (0)