Iterative approach:
def calculate_factorial(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
Recursive:
def calculate_factorial(n):
if n == 0:
return 1
else:
return n * calculate_factorial(n-1)
It would be great if you could share the code that you tried.
Answer from DASH on Stack OverflowVideos
Iterative approach:
def calculate_factorial(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
Recursive:
def calculate_factorial(n):
if n == 0:
return 1
else:
return n * calculate_factorial(n-1)
It would be great if you could share the code that you tried.
A possible method using a while loop:
factorial_base = int(input('Enter a positive integer:\n')) # The number to factorialize.
factorial = 1
if factorial_base > 0: # 0! = 1, so if the base is 0, just leave the factorial value as default (1).
while factorial_base != 1:
factorial *= factorial_base
factorial_base -= 1
Essentially, this will multiply 1 by the given number to factorialize (i.e. n), then by (n - 1), then by (n - 2), and so on, until the multiplication factor reaches 1.
Hope this helps.
The easiest way is to use math.factorial (available in Python 2.6 and above):
import math
math.factorial(1000)
If you want/have to write it yourself, you can use an iterative approach:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
or a recursive approach:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
Note that the factorial function is only defined for positive integers, so you should also check that n >= 0 and that isinstance(n, int). If it's not, raise a ValueError or a TypeError respectively. math.factorial will take care of this for you.
On Python 2.6 and up, try:
import math
math.factorial(n)
I have an assignment for class about a topic we never went over. Would appreciate help how to do it.
Write a script that inputs a nonnegative integer and computes and displays is facotrial. Try your script on the integers 10, 20, 30 and even larger values. Did you find any integer input for which Python could not produce an integer factorial value?
I have no idea where to start