Python asks for the sum of the factorial. Seeking 1+2!+3!+...+20! and

Source: Internet
Author: User

Factorial: Also a term in mathematics; factorial means multiplying from 1 times 2 times 3 times 4 to the required number; When expressing factorial, use "! "To express. such as h factorial, is expressed as h!; factorial is generally difficult to calculate, because the product is very large.

Analysis: 1, factorial calculation is a more troublesome part of the implementation of recursive function is a better solution, first define a recursive function to achieve the factorial function.

def  recursion (n):   # ' define recursive function for factorial function '    if n==1:        return 1    else:        return  n*recursion (n-1)

2, summing ideas, (1) can be summed directly. (2) You can also define a list, append the factorial result for the for traversal to the list, and then use the sum () function to sum.

Sum=0print ("For loop directly calls recursive function summation". Center ("*")) for  I in  range (1,21):    sum +=recursion (i) print (sum)  List sum scheme: list=[] #定义一个空的列表, append the factorial value generated by the calling recursive function to the list print ("Write the factorial of 1-20 to the list, sum with the SUM function." Center ("*")  )  Range (1,21):    list.append (Recursion (i) # appends the factorial value generated by the calling recursive function to the list print (sum (list)) #列表求和

Full source code and results:

def  recursion (n): # ' define recursive function for factorial function '    if n==1:        return 1    else:        return  n*recursion (n-1) list=[] #定义一个空的列表, append the factorial value generated by the calling recursive function to the list for  I in  range (1,21):    list.append (Recursion (i)) # Append the factorial value generated by the calling recursive function to the list print (SUM (list)) #列表求和Sum = 0for  i in  range (1,21):    sum +=recursion (i) print (sum) results: 2561327494111820313

Python asks for the sum of the factorial. Seeking 1+2!+3!+...+20! and

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.