Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Created January 29, 2020 08:10
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/d4d10a49136b36e1d7d2c5cf45e7ee4f to your computer and use it in GitHub Desktop.
Save Beraliv/d4d10a49136b36e1d7d2c5cf45e7ee4f to your computer and use it in GitHub Desktop.
Recursive solution to a task
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