Created
May 18, 2017 17:01
-
-
Save mayonesa/39094127eb117115182d0c84a7eacd84 to your computer and use it in GitHub Desktop.
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
log_factorial <- function (n) { | |
# Return the log of factorial(n) for any integer n > 0 | |
if (n <= 1) | |
return (0) | |
return (log(n) + log_factorial(n - 1)) | |
} | |
sum_log_factorial <- function (n) { | |
# Return the sum of log_factorial(i) for i in 1..n | |
sum <- 0 | |
for(i in seq(1, n, 1)) { | |
sum <- sum + log_factorial(i) | |
} | |
return (sum) | |
} | |
fibonacci <- function(n) { | |
# Return nth Fibonacci number | |
if (n <= 1) | |
return (n) | |
return (fibonacci(n - 1) + fibonacci(n - 2)) | |
} | |
time_f = function(f, n) system.time(f(n))[1] | |
options(expressions=500000) | |
time.complex <- function(ns, f) data.frame(seconds = sapply(ns, function(n) time_f(f, n)), Ns = ns) | |
ggp.time <- function(ns, f, lab) ggplot(time.complex(ns, f), aes(Ns)) + | |
geom_line(aes(y = seconds)) + | |
ggtitle(paste(lab, "Times", " ")) | |
ggp.time(c(50, 100, 200, 500, 1000, 2000, 3000), log_factorial, "Log Factorial") | |
ggp.time(c(50, 100, 200, 300, 500, 750, 1000, 1500, 2000, 2500, 3000), sum_log_factorial, "Sum Log Factorial") | |
ggp.time(c(5, 10, 15, 20, 25, 30, 35), fibonacci, "Fibonacci") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment