Sums of Perfect Squares (4kyu)
Description
The task is simply stated. Given an integer n
(3 < n < 109
), find the length of the smallest list of perfect squares which add up to n
. Come up with the best algorithm you can; you’ll need it!
Examples:
sum_of_squares(17) = 2
17 = 16 + 1 (16 and 1 are perfect squares).sum_of_squares(15) = 4
15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.sum_of_squares(16) = 1
16 itself is a perfect square.
Time constraints:
5 easy (sample) test cases: n < 20
5 harder test cases: 1000 < n < 15000
5 maximally hard test cases: 5e8 < n < 1e9
1000 random maximally hard test cases: 1e8 < n < 1e9
Solution
The task is based on Lagrange’s four-square theorem, any positive integer can be written as the sum of four or fewer number’s square.
Specially, if n = 4^k * (8 * m + 7)
, n
can not be the sum of 4
squares.
So, there are cases:
n
equals to the square of its root asu64
, return 1.- Use a loop to find out if
n
is sum of only 2 squares. - Check if
n
applys to the equation above, return 4 if yes or 3 else.
fn sum_of_squares(n: u64) -> u64 {
//case 1
let num = (n as f64).sqrt() as u64;
if (num*num) as u64 == n{
return 1;
}
//case 2
let end = (n as f64).sqrt() as u64;
for i in 1..=end{
let left = ((n - i*i) as f64).sqrt() as u64;
if left*left == (n - i * i) {
return 2;
}
}
//case 3
let mut remaining = n;
while remaining % 4 == 0{
remaining /= 4;
}
if remaining % 8 == 7{
return 4;
}
//case 4
return 3;
}