利用Python计算阶乘

    科技2024-11-28  18

    利用Python计算阶乘

    方法一

    直接利用嵌套循环进行编码

    def main(): a = int(input()) sum1 = 1 sum2 = 0 for i in range(1,a+1): for b in range(1,i+1): sum1 = b * sum1 sum2 = sum1 + sum2 sum1 = 1 print(int(sum2)) if __name__ == "__main__": main()

    方法二

    通过构造阶乘,再进行累加求和

    def main(): sum1 = 0 a = int(input()) for i in range(1,a+1): sum1 = function(i) + sum1 print(sum1) def function(n): if n == 1: return 1 else: return(n*function(n-1)) if __name__ == "__main__": main()
    Processed: 0.011, SQL: 8