Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active January 29, 2020 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beraliv/e6ae633c8ac3e54bed38eda75ba4f583 to your computer and use it in GitHub Desktop.
Save Beraliv/e6ae633c8ac3e54bed38eda75ba4f583 to your computer and use it in GitHub Desktop.
Recursive to iterative algorithm change
export const 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