Sum of First N Fibonacci Terms
Add the first n Fibonacci terms without storing a list. Students trace the starting pair, a running total, and the difference between terms and their sum.
1# Take n2n = int(input("Enter n: "))34# Calculate sum5if n <= 0:6 sum_fib = 07elif n == 1:8 sum_fib = 09elif n == 2:10 sum_fib = 111else:12 a, b = 0, 113 sum_fib = 1 # 0 + 114 for i in range(2, n):15 c = a + b16 sum_fib += c17 a, b = b, c1819print(f"Sum of first {n} Fibonacci terms: {sum_fib}")
Output
Enter n: 5 Sum of first 5 Fibonacci terms: 7
In this one
- Initialize a partial total
- Generate additional terms
- Sum rather than list
How it works
- 1
Handle counts through two directly.
- 2
Initialize a, b, and the sum of their pair.
- 3
Add each new Fibonacci term before shifting the pair.
Edge cases
What total is used for n = 1?
What total is used for n = 1?
Zero, because the only term is zero.
What happens for n <= 0?
What happens for n <= 0?
The program reports a total of zero rather than rejecting the input.
What's going on
The program totals Fibonacci values beginning with zero and one. n controls how many terms contribute, not how large a term may become.
For n greater than two, sum_fib begins at one to account for the first pair. Each new c is added once before the previous-term pair shifts forward. For five terms, zero, one, one, two, and three total seven.
What total is used for n = 1? Zero, because the only term is zero.
What happens for n <= 0? The program reports a total of zero rather than rejecting the input.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why initialize the longer-case total to one?
Pick an answer to check it.
Question 2
What total is used for n = 1?
Pick an answer to check it.
Questions people ask
What total is used for n = 1?
Zero, because the only term is zero.
What happens for n <= 0?
The program reports a total of zero rather than rejecting the input.
Why initialize the longer-case total to one?
The first pair already sums to one.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum