Created
January 29, 2020 08:10
-
-
Save Beraliv/d4d10a49136b36e1d7d2c5cf45e7ee4f to your computer and use it in GitHub Desktop.
Recursive solution to a task
This file contains hidden or 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 = []) => { | |
if (index < 0) { | |
return null; | |
} | |
if (index * index > rest) { | |
return decomposeWithIndex(rest, index - 1, currentResult); | |
} | |
if (index * index === rest) { | |
return [index, ...currentResult]; | |
} | |
// index * index < rest | |
const localAnswer = decomposeWithIndex(rest - index * index, index - 1, [index, ...currentResult]); | |
if (localAnswer === null) { | |
return decomposeWithIndex(rest, index - 1, currentResult); | |
} | |
return localAnswer; | |
} | |
return decomposeWithIndex(n * n, n - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment