Created
January 29, 2020 08:07
-
-
Save Beraliv/915780e0b3a83900addd5e1e81b1fe67 to your computer and use it in GitHub Desktop.
Iterative solution to a task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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