Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,... By considering the terms in the Fibonacci sequence whose values do not exceed 1000, find the sum of the all the terms up to 300, by writing a python program.
Note: I have a little confusion in the code, that up to which terms I need to sum in the series. However I have make a program that will add the elements till we don't encounter a no. greater than 300. If limit needs to be changed, by just changing the no. i the while loop will work.
Program:
#fibonacci list storing first 300 terms of series
fibonacci = [1, 2] + [0]*298
#generating all 300 terms by adding previous two each time
for i in range(2,298):
fibonacci[i] = fibonacci[i-1]+fibonacci[i-2]
#since we need to find sum, we'll use while loop
i = 0
#sum variable will store the sum of the series
sum = 0
#we'll traverse the list till we don't get a no. in series
#greater than 300
while fibonacci[i]<300:
#adding the no.
sum += fibonacci[i]
#for moving to the next value
i+=1
#print statement
print("The sum of the series of first {} terms: {}".format(i+1, sum))
Output:
The sum of the series of first 13 terms: 608
Leave a comment if face any kind of doubt!!
Get Answers For Free
Most questions answered within 1 hours.