Skip to content

Instantly share code, notes, and snippets.

@Smerity
Last active August 29, 2015 13:56
Show Gist options
  • Save Smerity/8902470 to your computer and use it in GitHub Desktop.
Save Smerity/8902470 to your computer and use it in GitHub Desktop.
Fib in C, Python, PyPy, R, and R (JIT)
#include "assert.h"
#include "stdio.h"
unsigned long long int fib(int n) {
assert(n >= 0);
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}
int main(int argc, const char *argv[])
{
int i;
for (i = 0; i < 35; ++i) {
printf("%llu\n", fib(i));
}
return 0;
}
def fib(x):
if x < 2:
return x
return fib(x - 1) + fib(x - 2)
for i in xrange(35):
print i, fib(i)
require(compiler)
enableJIT(3)
fib = function(x) {
if (x < 2) {
return(x)
}
return(fib(x - 1) + fib(x - 2))
}
for (i in 1:34) {
print(i)
print(fib(i))
}

R: 2 minutes 45 seconds
R (JIT): 1 minute 11 seconds
Python: 8.198 seconds
PyPy (Python JIT): 1.519 seconds
C: 0.151 seconds

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