I am working on a Python homework that asks me to code the Sieve of Sundaram:
*- start with a list of numbers from 1 to n;
- for every pair of integers i and j where 1<= i <= j and i + j + 2ij <= n, remove i + j + 2ij from - the list above;
- finally, for each remaining number k in the list, 2k+1 is a prime number.*
This is my code:
n = int(input())
num_lst = list(range(1, n + 1))
for i in num_lst:
for j in num_lst:
if (1 <= i <= j) and (i + j + (2 * i * j)) <= n:
num_lst.remove((i + j + (2 * i * j)))
print(num_lst)
for idx, k in enumerate(num_lst):
num_lst[idx] = 2 * k + 1
print(num_lst)
I see many solutions that uses list comprehensions, but at this point of the class, we have not covered it yet.
When input is 50, I'm getting prime numbers up until 101; but I'm also getting some that are not primes (27, 45, 63, 99). What did I do wrong?
Tried this:
OUTPUT: