Attempt of Eratosthenes sieve in python

2

Hi, I'm trying to make a code using the Eratosthenes Screen method but I get confused in the part of multiplying and eliminating the number that is not prime, the teacher says we should use a del or something to eliminate the number what is in the list but not how is the syntax or anything.

n=int(raw_input("Ingrese un numero: "))
lista=[]
i=2
i2=1
cont=0
while i<n:
   lista.append(i)
   i+=1
   while cont <n:
      yu=cont*i
      if yu == lista[]
print lista    

This is what I carry and I confuse myself in how to do the rest, if you can help me I would be very grateful

    
asked by Wolf 19.10.2018 в 05:32
source

2 answers

3

There are multiple ways to solve this problem. As you mentioned that you should "%" usar un del o algo asi then starting that way, what I did was to generate a list starting from 2 to the number entered by keyboard. Then iterate with a while while the square of the current element is less than or equal to the number entered by keyboard. Then a for will scroll through all the current numbers in the list and ask if that number is divisible by the current element of the while. If so, then it is deleted from the list, altering it.

When the square of the current element (of the while) is greater than the number entered by the keyboard, the program and the resulting list are finished with pure prime numbers.

n = int(raw_input("Ingrese un numero: "))
lista = list(range(2, n+1))

i = 0
while(lista[i]*lista[i] <= n):
    # Mientras el cuadrado del elemento actual sea menor que el ultimo elemento
    for num in lista:
        if num <= lista[i]:
            # Cada iteracion del while hace que el for comience desde el primer elemento. 
            # Esto es para omitir los numeros primos ya encontrados
            continue
        elif num % lista[i] == 0:
            # Si un numero es divisible entre el elemento actual del while
            # de ser asi, entonces eliminarlo de la lista (esto altera la lista)
            lista.remove(num)
        else:
            # Si no es divisible, entonces omitirlo (no hacer nada)
            pass
    i += 1 # Incrementa al siguiente elemento de la lista (que ha sido alterada)

print lista
    
answered by 19.10.2018 / 08:01
source
0
# Versión que imprime por consola el método de eratóstenes.

numero_tope = int(input("Ingrese un numero: "))
casillas = {}

# Se construye un diccionario con el universo de números disponibles
for casilla in range(2, numero_tope + 1):
    casillas[casilla] = str(casilla)


def buscarMultiplos(numero_base):
    multiplos = []
    for numero in range(numero_base + 1, numero_tope + 1):
        if(numero % numero_base == 0):
            multiplos.append(numero)
    return multiplos

def mostrarResultado():
    salida = []
    #casillas[3] = "aasd"
    for casilla in casillas:
        if(casillas[casilla].isdigit()):
            salida.append(str(casilla))
        else:
            salida.append("X")
    print(" - ".join(salida))

"""
Pasos desde https://es.wikipedia.org/wiki/Criba_de_Erat%C3%B3stenes

1.- Listar los números naturales comprendidos entre 2 hasta el número que se desee.
2.- Se toma el primer número no marcado como número primo.
3.- Se marcan todos los múltiplos del número que se acaba de indicar como primo.
4.- Si el cuadrado del primer número que no ha sido marcado es inferior al numero_tope,
    entonces se repite el segundo paso. Si no, el algoritmo termina, y todos los
    enteros no tachados son declarados primos.
"""
mostrarResultado()

for valor in casillas:
    if(casillas[valor] == "X"):
        continue

    for numero in buscarMultiplos(valor):
        casillas[numero] = "X"
    mostrarResultado()
    if(valor ** 2 > numero_tope):
        break
    
answered by 21.10.2018 в 05:05