Problem 1: Factorial (100pts)
Problem
Write a function that takes a non-negative integer \(n \ge 0\) and returns its factorial.
Factorial of \(n\) is defined as
\[n!=\prod_{i=1}^ni=1\times2\times3\times\cdots\times n.\]
编写一个函数,接受一个非负整数 \(n \ge 0\),并返回它的阶乘。
\(n\) 的阶乘定义为:
\[n!=\prod_{i=1}^ni=1\times2\times3\times\cdots\times n.\]
def factorial(n):
"""Return the factorial of a non-negative integer n.
>>> factorial(3)
6
>>> factorial(5)
120
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: You may want to use a
while
loop to solve this problem. Be careful when to stop!Hint2: What is the factorial of 0?
Hint3: Use return to
return
the result, don't
-
你可能希望使用
while
循环来解决这个问题。注意何时停止循环! -
0 的阶乘是多少?
-
使用
return
来返回结果,不要print
它。这是定义函数的正确方式。 -
while
循环可以解决这个问题,递归也可以。
Solutions
使用 while
循环:
def factorial(n):
if n == 0:
return 1
result = 1
current_number = 1
while current_number <= n:
result *= current_number
current_number += 1
return result
使用 for
循环:
def factorial(n):
if n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
递归:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)