1

I wrote a program to calculate the factorial of a number, and store the digits of the result in a Python list.

  1. To find the factorial, I run a loop that takes O(N) and store the result in "ans"
  2. To find the number of digits of "ans", I run another loop that takes log10(ans).
  3. Finally, I just reverse the list in-place

I am struggling to see what the total Time Complexity (TC) is. I believe:

TC = O(d) = O(log10(ans)), since d > N for N->inf, where d (number of digits in ans) = log10(ans), and ans ∈ O(N).

Am I wrong? Is there any other way to express the total TC, maybe something like a nested Big-O:

O(log10(O(N))) ???

Note: log10 means logarithm with base 10

Below is my code:

def factorial(N):
        ans = N
        ans_digits = []

        # 1. O(N)
        while N > 1:
            N -= 1
            ans *= N

        # 2. O(log10(ans))
        while ans > 0:
            digit = ans % 10
            ans //= 10
            ans_digits.append(digit)

        # 3. O(log10(ans))
        for i in range(len(ans_digits)//2):
            temp = ans_digits[i]
            ans_digits[i] = ans_digits[-(i+1)]
            ans_digits[-(i+1)] = temp

        # Shorter way of doing 2 and 3: O(log10(ans))
        #ans_digits = str(ans).split()

        return ans_digits
karahbit
  • 93
  • 10
  • 1
    Yes, TC = O(d) because d > N for large N. To express O(d) in terms of N, you need to use [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation). – user3386109 Sep 20 '21 at 23:35
  • 1
    Or you can just approximate TC by noting that most of the multiplications will add O(logN) digits to the answer. Either way, the time complexity expressed in terms of N is O(NlogN). – user3386109 Sep 20 '21 at 23:41
  • @user3386109: Correct me if I am wrong then. So TC = O(d) = O(logn!) = O(nlogn - c.n + O(logn)) = O(nlogn) ? – karahbit Sep 21 '21 at 00:01
  • Yes, that's correct. – user3386109 Sep 21 '21 at 00:55

1 Answers1

1

Thanks to @user3386109, by Stirling's approximation to factorials, the Time Complexity can be expressed in terms of N as:

TC = O(d) = O(logN!) = O(NlogN - c.N + O(logN)) = O(NlogN)

where log has base 10 and N is an integer.

nullptr
  • 3,701
  • 2
  • 16
  • 40
karahbit
  • 93
  • 10
  • 1
    for Big-O we don't really care if log is base10 or base2 or base whatever, they because they differ only by a constant. – AminM Sep 21 '21 at 06:02