forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumOfSquares.java
More file actions
53 lines (46 loc) · 1.23 KB
/
SumOfSquares.java
File metadata and controls
53 lines (46 loc) · 1.23 KB
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
53
package com.thealgorithms.maths;
/**
* Implementation of Lagrange's Four Square Theorem
* Find minimum number of perfect squares that sum to given number
*
* @see <a href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem">Lagrange's Four Square Theorem</a>
* @author BEASTSHRIRAM
*/
public final class SumOfSquares {
private SumOfSquares() {
// Utility class
}
/**
* Find minimum number of perfect squares that sum to n
*
* @param n the target number
* @return minimum number of squares needed
*/
public static int minSquares(int n) {
if (isPerfectSquare(n)) {
return 1;
}
for (int i = 1; i * i <= n; i++) {
int remaining = n - i * i;
if (isPerfectSquare(remaining)) {
return 2;
}
}
// Legendre's three-square theorem
int temp = n;
while (temp % 4 == 0) {
temp /= 4;
}
if (temp % 8 == 7) {
return 4;
}
return 3;
}
private static boolean isPerfectSquare(int n) {
if (n < 0) {
return false;
}
int root = (int) Math.sqrt(n);
return root * root == n;
}
}