LoginSignup
0
0

factorial Factorial (階乗)

Posted at

階乗 (nの階乗=n!)

factorial Factorial について

recur_factorial.py

def recur_factorial(n):
  if n == 1:
      return n
  else:
      return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
  print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
  print("The factorial of 0 is 1")
else:
  print("The factorial of", num, "is", recur_factorial(num))

Memo

time complexities O(n!)
Use stack Data Stracture
recursive funnction

n Factorial n (n - 1) (n - 2) ....1 n! = n × (n - 1)! Result
1 Factorial 1 1 1
2 Factorial 2 × 1 = 2 × 1! = 2
3 Factorial 3 × 2 × 1 = 3 × 2! = 6
4 Factorial 4 × 3 × 2 × 1 = 4 × 3! = 24
5 Factorial 5 × 4 × 3 × 2 × 1 = 5 × 4! = 120

Fomula

n! = n \times (n - 1) \times (n - 2) \times \ldots \times 2 \times 1

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0