0

Calculating the factorial n! by the algorithm that defines it is of O(n) complexity because it requires n-1 multiplications to find the solution. Is there an algorithm that is any faster than that?

magnetlion
  • 113
  • 1
  • 6

1 Answers1

2

If you want to get into technicalities, computing the factorial actually takes more than $O(n)$ time: One way to notice this is that $n!$ as a number has $\Theta(n \log n)$ digits. It will therefore take at least $\Theta(n \log n)$ time to even write the answer, so computing the answer will take at least that long.

That being said, can you compute $n!$ in $O(n \log n)$ time? Yes, but you have to be a little careful. The pseudocode

product = 1
for i from 1 to n:
    product = product * i

Is too slow, because at during the second half of the for loop, you end up multiplying $O(n)$-digit numbers $O(n)$ times, and you would end up with an algorithm that is at least quadratic.

A more efficient way is to divide and conquer: Starting with a list of numbers $1$ through $n$, pair the numbers up and multiply. Then do this again and again until you have a single number. In the $i^{\text{th}}$ iteration, you multiply $O(n/2^i)$ pairs of $O(2^i \log n)$-digit numbers. If we use a multiplication algorithm which takes $O(d \log d)$ time for $d$-digit numbers, then the $i$th iteration takes $O(n (\log n) \cdot \log(2^i \log n)) = O(n (\log n) i + n (\log n) (\log (\log n)))$ time. Summing for $i$ going from 1 to $\log n$, we get $O(n \log(n)^2 (\log (\log n)))$.

Even faster is to decompose the prime factors of the numbers below $n$. More details in this paper


By the way you are asking the question though, it seems like you are more interested in a model of computation where multiplication of integers takes a single step, and you want the answer to the question "How many multiplications do you have to do to compute the factorial?". In this case the answer is O(n), simply because if we treat the numbers we have to multiply as given and the multiplication algorithm as a black box, each multiplication has two inputs and one output, so it only reduces the list of numbers we have to multiply by 1.

Bolton Bailey
  • 258
  • 1
  • 7