Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 10 of 14
sum-of-first-n-fibonacci-terms.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate sum
5if n <= 0:
6 sum_fib = 0
7elif n == 1:
8 sum_fib = 0
9elif n == 2:
10 sum_fib = 1
11else:
12 a, b = 0, 1
13 sum_fib = 1 # 0 + 1
14 for i in range(2, n):
15 c = a + b
16 sum_fib += c
17 a, b = b, c
18
19print(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. 1

    Handle counts through two directly.

  2. 2

    Initialize a, b, and the sum of their pair.

  3. 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.