Primes from 1 to 100

EasyFunction Programs · 26 of 39

Write a Python function that returns the prime numbers from 1 to 100.

Advertisement
Output
25 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Approach

  1. Reuse a prime test inside a comprehension.

Solution

Python
def is_prime(n):    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) def primes_upto(limit):    return [n for n in range(1, limit + 1) if is_prime(n)] primes = primes_upto(100)print(len(primes), primes)
Output
25 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Advertisement

Learn the concept

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

More function programs

← All 39 Function Programs