The problem you are going to solve is the following: Compute the sum of n! and o
ID: 3774193 • Letter: T
Question
The problem you are going to solve is the following: Compute the sum of n! and only output the sums divisible by 7 for the range 0 lessthanorequalto n lessthanorequalto 10^6. For example: n = 1: sum = 1! = 1 n = 2: sum = 1! + 2! = 1 + 2*1 = 3 n = 3: sum = 1! + 2! + 3! = 1 + 3 + 3*2*1 = 10 n = 4: sum = 10 + 4*3*2*1 =34 n = 5: sum = 34 + 5*4*3*2*1 = 154 You are to provide these implementations: Python using recursion (e.g., a function that calls itself) Python using a functional approach with the filter function (see the previous lecture). Your solution should contain the following: The source code (keep it simple and strip the comments so the code footprint is small) Proof that the code ran properly and produced the correct output (provide a screenshot showing a timestamp and the output) An analysis of how long the code took to run. A discussion comparing the approaches and explaining which one ran faster and why. Your solutions will be graded based on the simplicity of your code, the correctness of your output and the insightfulness of your analysis.Explanation / Answer
Solution:
# recursive method to compute the factorial of a number
def recfactorial(n):
if n == 1:
return n
else:
return n*recfactorial(n-1)
# method to compute sum of factorial and find sum divisible by 7
def sumdiv7(n):
# list to store sum
factlist=[]
# loop to compute factorial
for i in range(1,n+1):
sum=0
for j in range(1,i+1):
sum=sum+recfactorial(j)
if i>2:
sum=sum+1
factlist.append(sum)
print "The sum of factorial is", factlist
# filter to find a sum value divisible by 7
result=filter(lambda x:x%7==0,factlist)
print "The sum divisible by 7 is",result
Result:
>>> sumdiv7(5)
The sum of factorial is [1, 3, 10, 34, 154]
The sum divisible by 7 is [154]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.