I wrote a Racket program to calculate factorials and ran tests to see how the runtime scaled with different values of n for n!. I was surprised to see that sometimes when scaling n, it caused little increases in the runtime but other times the difference was massive. For instance, increasing n from 10 to 100 increased the runtime by about 8x; scaling n from 1000 to 10000 increase runtime by 380x and scaling n from 10000 to 100000 increased runtime by about 42x.
I was expecting the runtime to either scale linearly or according to some type of formula.
Here’s the code:
#lang racket
(define (factorial-recursive n)
(define (fact-iter n p)
(if (= n 1)
1
(fact-iter (- n 1) (* p n))))
(fact-iter n 1)
)
(define (factorial-iterative n)
(define (iter c p n)
(if (> c n)
1
(iter (+ c 1) (* p c) n))
)
(iter 1 1 n)
)
(define (time-iterative-factorial t )
(define x (current-inexact-milliseconds))
(factorial-iterative t)
(- (current-inexact-milliseconds) x)
)
(define (time-recursive-factorial t)
(define x (current-inexact-milliseconds))
(factorial-recursive t)
(- (current-inexact-milliseconds) x)
)
(time-recursive-factorial n)
Here's a table that shows how the runtime scales with different values of n: