Skip to content

Instantly share code, notes, and snippets.

@voila voila/fact.js
Created Jul 3, 2019

Embed
What would you like to do?
Factorial recursive to iterative
let fact0 = (n) => {
if (n > 0) {
return n * fact0(n - 1);
} else
return 1;
}
console.log(fact0(5, (x) => x))
let fact1 = (n, k) => {
if (n > 0) {
return fact1(n - 1, (x) => k(n * x))
} else {
return k(1)
}
}
console.log(fact1(5, (x) => x))
// type cont = {n:int , k:cont} | null
let fact2 = (n, k) => {
let res = 1;
while (true) {
if (n > 0) {
k = { n: n, next: k }; // new cont (stack push)
n = n - 1;
} else {
if (k != null) {
res = res * k.n;
k = k.next; // (stack pop)
}
else
return res;
}
}
}
console.log(fact2(5, null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.