Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Created January 29, 2020 08:07
Show Gist options
  • Save Beraliv/915780e0b3a83900addd5e1e81b1fe67 to your computer and use it in GitHub Desktop.
Save Beraliv/915780e0b3a83900addd5e1e81b1fe67 to your computer and use it in GitHub Desktop.
Iterative solution to a task
export class G964 {
public static decompose = (n: number) => {
const decomposeWithIndex = (rest: number, index: number, currentResult = []) => {
var repeat = true;
var saved = [];
while (repeat) {
repeat = false;
if (index < 0) {
if (saved.length > 0) {
const lastSaved = saved.pop();
rest = lastSaved.rest;
currentResult = lastSaved.currentResult;
index = lastSaved.index;
repeat = true;
continue;
}
return null;
}
if (index * index > rest) {
index = index - 1;
repeat = true;
continue;
}
if (index * index === rest) {
return [index, ...currentResult];
}
// index * index < rest
saved.push({
rest,
index: index - 1,
currentResult,
});
rest = rest - index * index;
currentResult = [index, ...currentResult];
index = index - 1;
repeat = true;
}
}
return decomposeWithIndex(n * n, n - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment