Reputation:
The statement says:
Write a function
era1()
that ask the user for a numbern
and then use this algorithm to print all prime numbers less than or equal ton
.Algorithm:
- Write a list with numbers from 2 to largest integer N you want to calculate.
- The first number in the list is a prime number. Write this number a list of primes,
B
.- Remove from the list
A
, the first element and its multiples.- If the first number in the list
A
is less than the square root N, come back to second point.- The numbers in the
B
list and those left in ListA
are all primes searched.
Now, I put this code:
import math
def primo(num):
if num < 2:
return False
i = 2
for i in range(2, int(math.sqrt(num) + 1)):
if (num % i == 0):
return False
return True
def main():
n = input("Introdueix un nombre: ")
B = range(2, n)
for i in B:
if primo(i):
print i
main()
def era1():
n = input("Introdueix un nombre: ")
A = range(2, n + 1)
B = [A[0]]
for i in A:
if i % 2 == 0:
A.remove(i)
if A[0] < math.sqrt(n):
print B + A
era1()
The result is incorrect because if I remove one of the input, appears error and I have to put only one time the input. Also the result is incorrect because the A + B
, the list B
is not the list of function main and the final result is only the numbers not multiples of 2 and 2. How can I put only one input and then the final result will be correct?
Upvotes: 0
Views: 7034
Reputation:
This Algorithm is called Sieve of Eratosthenes.
It is a simple algorithm for finding all prime numbers up to a specified integer. It was created in the 3rd century BC by Eratosthenes, an ancient Greek mathematician.
In order to develop this algorithm, we'll go through the different above-mentioned steps.
A = range(2, n + 1)
We use another list C, as we might use A later to print the initial list.
We go through C, processing all the numbers less than the square root N.
(x%firstElement!=0)
.C= [x for x in C if x%firstElement!=0]
Your code should look like:
def era1():
n = input("Introduce a nombre: ")
#n=120 #To test the
A = range(2, n + 1)
B, C= [],A
while C[0]< math.sqrt(n): #Condition
firstElement= C[0]
B+= [firstElement] #The first number in the list is a prime number. Write this number a list of primes, B.
C= [x for x in C if x%firstElement!=0] #We use comprehension List to filter multiplies using
return B+C #The numbers in the B list and those left in List A are all primes searched.
print era1()
Output in case of n=120: [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, 101, 103, 107, 109, 113]
This picture visualize the Algorithm, Source of picture.
Upvotes: 2
Reputation: 23753
Removing items from a list while iterating over it will have unexpected results, it interferes with the indexing.
a = [1,2,3,4,5,6,7,8,9]
for thing in a:
a.remove(thing)
>>> a
[2, 4, 6, 8]
>>>
You will need to figure out another way to accomplish that - perhaps create a new list with the items you want to keep.
Upvotes: 0