Week 4: Homework Solutions

3.

# Use the sieve of Eratosthenes to find prime numbers
n = int(input("Enter a positive integer: "))
numbers = list(range(2, n+1))
# we look at numbers up to sqrt(n)+1
for i in range(2, int(n**0.5) + 2):
    # we remove multiples of i from the list
    for j in range(2*i, n+1, i):
        if j in numbers:
            numbers.remove(j)
print(numbers)
print("\nThere are", len(numbers), "prime numbers up to", n)

4.

# To find numbers equal to the sum of cubes of the digits
for i in range(2, 1000):
    sum_of_cubes = 0
        for p in str(i):
            sum_of_cubes = sum_of_cubes + int(p)**3
    if sum_of_cubes == i:
        print(i)