描述
给定一个数n,返回该数的二阶阶乘。在数学中,正整数的二阶阶乘表示不超过这个正整数且与它有相同奇偶性的所有正整数乘积。
∙ \bullet ∙结果一定不会超过long。
∙ \bullet ∙n是一个正整数
样例
样例1:
输入: n = 5
输出: 15
解释:
5!! = 5 * 3 * 1 = 15
样例2:
输入: n = 6
输出: 48
解释:
6!! = 6 * 4 * 2 = 48
class Solution:
"""
@param n: the given number
@return: the double factorial of the number
"""
def doubleFactorial(self, n):
# Write your code here
ans = 1
for i in range(n,-1,-2):
if i != 0:
ans = ans * i
return ans
普通递归:
class Solution:
"""
@param n: the given number
@return: the double factorial of the number
"""
def doubleFactorial(self, n):
# Write your code here
if n <= 2:
return n
return n * self.doubleFactorial(n-2)
尾递归:
class Solution:
"""
@param n: the given number
@return: the double factorial of the number
"""
def doubleFactorial(self, n, result=1):
if n <= 2:
return n * result
return self.doubleFactorial(n-2,result * n)
尾递归直接翻译过来的迭代版本:
class Solution:
"""
@param n: the given number
@return: the double factorial of the number
"""
def doubleFactorial(self, n, result=1):
while True:
if n <= 2:
return n * result
next_n, next_result = n - 2, n * result
n, result = next_n, next_result