Skip to content

Instantly share code, notes, and snippets.

@frankkienl
Created August 19, 2014 17:23
Show Gist options
  • Save frankkienl/8862e7848e637d114398 to your computer and use it in GitHub Desktop.
Save frankkienl/8862e7848e637d114398 to your computer and use it in GitHub Desktop.
Proof that some functions do not need to be recursive.
//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;
@frankkienl
Copy link
Author

All functions give the same results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment