The problem:
"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:
An even-valued term is dividable by 2. When starting to write a for loop I got this:
which might be useful. Since the steps I'll be iterating will change, a while-loop might be more useful in this case. How does Python use while-loops? I found a while-loop-example here, which I modify to run on Python 3.
"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 four million, find the sum of the even-valued terms."An even-valued term is dividable by 2. When starting to write a for loop I got this:
which might be useful. Since the steps I'll be iterating will change, a while-loop might be more useful in this case. How does Python use while-loops? I found a while-loop-example here, which I modify to run on Python 3.
count = 0while (count < 9): print('The count is:', count) count = count + 1 print("Good bye!")
This is how I'm setting up my variables for the first loop: 1, 2, 3. Next loop will shift the three variables to the right on step so that "previous" is 2, "current" is 3 and "next" is 5.
previousNumber = 1currentNumber = 2nextNumber = 3fourM = 4000000sum = currentNumber while (nextNumber < fourM): nextNumber=previousNumber+currentNumber previousNumber=currentNumber currentNumber=nextNumber if nextNumber<fourM and nextNumber%2==0: sum+=nextNumber print("Sum: ", sum)
/Ludvig
No comments:
Post a Comment