I have a question as follows:
Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².
decompose(11) must return [1,2,4,10]. Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return [2,6,9], since 9 is smaller than 10 (if multiple sequence of squared integers can be used, go with the greatest one - so 10 instead of 9 in the above case).
For decompose(50) don't return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn't form a strictly increasing sequence.
I have gotten nowhere, trying this (which probably is poorly done):
function sq2squares($n) {
$starting = ($n - 1) ** 2;
$square = $n**2;
$range = range(1, $n -1);
$start = $square - $starting;
foreach($range as $r => $v) {
if($v**2 > $start) {
unset($range[$r]);
}
}
# $range here is [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach(array_reverse($range) as $r) {
if($r**2 < $start) {
$start -= $r**2;
}
}
print_r($results); // [49] || Should be: [1,3,5,8,49]
}
I have subtracted square of input from largest next number (49) which leaves 99. Then I want to iterate over the remaining integers in $range (9-1) and subtract each but ONLY if the resulting subtraction results in $start being 0. That last part is what I can't figure out.
How to iterate over the array $range and only array_push() values which result in $start being 0? Thanks.