Python Practice › Loop Programs › Program 33

Sum of primes from 1 to n

EasyLoop Programs · 33 of 90

Write a Python program to find the sum of all prime numbers from 1 to n.

Advertisement
Input
n = 100
Output
Sum of primes up to 100: 1060

Approach

  1. Reuse a prime test and add the primes.

Solution

Python
def is_prime(n):    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) total = 0for n in range(1, 101):    if is_prime(n):        total += nprint("Sum of primes up to 100:", total)
Output
Sum of primes up to 100: 1060

Line by line

Line 2

all(n % d ...) is True when every remainder is non-zero, meaning no divisor exists.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Leave a Comment