Created
August 19, 2014 17:23
-
-
Save frankkienl/8862e7848e637d114398 to your computer and use it in GitHub Desktop.
Proof that some functions do not need to be recursive.
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
//Recursive | |
function A(n){ | |
if (n <=0){return 0;} | |
return 1 - (1 - A( n - 1)) / 2; | |
} | |
//Not recursive, using a loop | |
function B(n){ | |
if (n<=0){return 0;} | |
//TODO insert smart code here | |
answer = 1; | |
for (i=0; i<n; i++){ | |
answer = answer/2; | |
} | |
return 1 - answer; | |
} | |
//Optimized, not recursive, no loop | |
function C(n){ | |
if (n<=0){return 0;} | |
//TODO insert even smarter code here | |
return 1 - (1/(Math.pow(2,n))); | |
} | |
var resultString = "<table border=1>"; | |
for (i=0; i<=25; i++){ | |
resultString += | |
"<tr>" + | |
"<td>A(" + i + ")=" + A(i) + | |
"<td>B(" + i + ")=" + B(i) + | |
"<td>C(" + i + ")=" + C(i) + | |
"</tr>\n"; | |
} | |
resultString += "</table>"; | |
document.getElementById('result').innerHTML = resultString; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All functions give the same results.