JavaScript (ES6), 65 64 bytes
f=(a,i=1)=>a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a<i?0:[i]
Returns an array if there's a solution, or 0 for no solution.
This is a highly inefficient yet golfy solution to the problem.
It searches for the first solution using a-i
and i=1
, even if it doesn't work up the recursive stack. If that solution doesn't begin with i+2
, then we recursively search for the first solution using a
and i+2
.
Ungolfed
f=(a,i=1)=>
a > i ?
(c = f(a - i, i += 2))[0] == i ?
[i-2, ...c] :
f(a, i) :
a < i ?
0 :
[i]
Test cases:
f=(a,i=1)=>a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a<i?0:[i]
console.log(JSON.stringify(f(1))); //[1]
console.log(JSON.stringify(f(3))); //[3]
console.log(JSON.stringify(f(4))); //[1, 3]
console.log(JSON.stringify(f(5))); //[5]
console.log(JSON.stringify(f(6))); //[0]
console.log(JSON.stringify(f(9))); //[1, 3, 5]
console.log(JSON.stringify(f(15))); //[3, 5, 7]
console.log(JSON.stringify(f(104))); //[23, 25, 27, 29]
For an idea of how inefficient this is, the solution to f(104)
requires 69,535 recursive calls. The stack is never more than 51 levels deep, so no problem with stack overflow.
The solution to f(200)
requires 8.6 million recursive calls, with a stack 99 levels deep. (Its solution is [11,13,15,17,19,21,23,25,27,29]
.)
Here's a visual representation of the program running:
r=0;
output=o=>setTimeout(_=>O.textContent += o + '\n', r++ * 20);
f=(a,i=1,s='',o = s + 'a=' + a + '; i=' + i + ';')=>
(
output(o),
a > i ?
(c = f(a - i, i += 2, s + ' '))[0] == i ? (
output(o + ' a > i; [i-2, ...c] = [' + [i-2, ...c] + '];'),
[i-2, ...c]
) : (
output(o + ' a > i; c=[' + c + ']; ' + 'c[0]+2 != i ... dead end\n' + s + 'trying a, i+2:'),
f(a, i, s)
) :
a < i ? (
output(o + ' a < i ... dead end'),
0
) : (
output(o + ' a == i;'),
[i]
)
)
f(21); //[5, 7, 9]
<pre id=O></pre>