• + 13 comments

    In Python 3.

    We know that factorial of 1 and 0 is 1, after that we have what we have

    def factorial(n):
        if n <= 1:
            return 1
        else:
            result = n * factorial(n - 1)
            return result
            
    
    • + 0 comments

      this is awesome <3

    • + 1 comment

      Nice job. However, you can skip the result variable and just return the arithmetic.

      return n * factorial(n - 1)

      • + 0 comments

        This code won't stop until it exceeded the recursion depth as you didn't give it a stop point.


        def factorial(n):
        	return n * factorial(n-1) if n > 1 else 1
        
    • + 0 comments

      Can you explain how the factorial in result = n * factorial(n - 1) works?

      By the time the computer traverses tofactorial, the function hasn't been finished defining.

      Thanks!

    • + 0 comments

      use memoization or lru_cache to reduce the usage of processing power

    • + 0 comments

      Same solution with cached memmory so the function doesn't have to repeat itself every time:

      factorial_cache = {}
      
      def factorial(n):
          # Memoization: Return the value we have cached
          if n in factorial_cache:
              return factorial_cache[n]
      
          # Factorial Part
          if n <= 1:
              value = 1
          else:
              value = n*factorial(n-1)
      
          # Cache the value
          factorial_cache[n] = value
          return value
      
    • + 0 comments

      In my original code I wrote print('1') instead of return 1 and the compiler showed error. Can somebody tell me why this happened. It showed * can't be done in between an int and a nontype

    • + 0 comments

      showing error no response on stdoutput

    • + 1 comment

      def factorial(n): fact = 1 if n < 0: return "Not Exist" elif n == 0: return 1 else: for i in range(1, n + 1): fact *= i return fact

      • + 0 comments

        Non recursive

    • + 0 comments

      presized

      def factorial(n):
          if n==0:
              return 1
          return n*factorial(n-1)
      
    • + 0 comments

      Well then I think the condition should be n == 1 or n == 0. As n <= 1 will also take negative numbers into consideration whose factorials cannot be calculated.

    • + 0 comments

      i started from factorial 1. here is my code:

      factorial_number = 1 if n >= 1: for n in range(1,n + 1): factorial_number = factorial_number * n print(factorial_number)
      return factorial_number

    • + 0 comments

      Javascript with memoization (Dynamic Programming) for better performance:

      function factorial(n) {
          const memo = {1: 1, 2: 2}
          let f = n => memo[n] ? memo[n] : (memo[n] = n * f(n-1))
          return f(n)
      }