函數(shù)fact(n):計(jì)算階乘
fact(n) = n! = 1x2x3x ... x (n-1)x n = (n-1)! x n = fact(n-1) x n
故act(n)可以表示為n x fact(n-1),只有n=1時(shí)需要特殊處理。
所以可以在n=1時(shí),返回1
于是代碼:
#! /usr/bin/python3# -*- coding:UTF-8 -*-def fact(n): if n==1: return 1 return n * fact(n - 1) print(fact(5))