ByteBoard Notes Notes

To find the sum of squares of the first 100 natural numbers

Informatics Practices XI · Experiment 10 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.10
Page No.20

Sum of squares of 1 to 100

Aim

To write a Python program that finds the sum of the squares of the first 100 natural numbers (1² + 2² + … + 100²).

Concepts used

Algorithm

  1. Set total = 0.
  2. For i from 1 to 100, add i × i to total.
  3. Display total and check it with the formula n(n+1)(2n+1)/6.

Program

# Sum of squares of the first 100 natural numbers total = 0for i in range(1, 101):    total = total + i * iprint("Sum of squares (loop)   :", total)n = 100print("Sum of squares (formula):", n * (n + 1) * (2 * n + 1) // 6)

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python sum_of_squares.py
Sum of squares (loop) : 338350 Sum of squares (formula): 338350

✓ Printed by running this program, not typed by hand.

Result

The loop gave 338350, the same as the formula 100 × 101 × 201 ÷ 6.

Viva voce: what the examiner may ask

01Why is the stop value of range() 101 and not 100?

The stop value is not included, so range(1, 101) gives 1 to 100.

02What does // do?

Floor division: it divides and drops the decimal part, giving an integer here.

03How would you write the loop with while?

Start i at 1, loop while i <= 100, add i * i and increase i by 1.

Variations for the lab test

  1. Find the sum of cubes of the first 50 natural numbers.
  2. Find the sum of squares of the first n numbers for a user-entered n.
  3. Find the sum of squares of only the even numbers up to 100.
! Common mistake Using range(100) starts at 0 and stops at 99, so 100² (10000) is left out.
Back to the 11-IP index