Created
July 3, 2019 22:06
-
-
Save voila/7243e7c1a856a3c47074f12413b2fa9c to your computer and use it in GitHub Desktop.
Factorial recursive to iterative
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
| 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