See which elements of the list are primes

Asked

Viewed 252 times

1

Hello, I am making a list of exercises and I came across a question consisting of reading the elements of a list and determining how many are cousins.

I could only do the function to calculate the prime numbers, but I can’t do for the whole list, someone can help me?

def primos(x)
    entrada = int(input())
    contadora = 1
    divisores = 0

    while contadora <= entrada:
        if entrada%contadora==0:
            divisores += 1
            contadora += 1
        else:
            contadora += 1
    if divisores != 2:
        print ('nao eh primo')
    elif divisores == 2:
        print ('eh primo')

I think a solution would be to read the list by parameter in a function 2 and call the function "primes" for each element of the function list 2 (list[i]), but I don’t know how to write this...

1 answer

0

The function used to check whether a number is prime in this response is based on reply of Dawg in the Stack Overflow. This function is much more efficient because it is only necessary to check up to the square root of n to know if n is cousin. There are other ways to implement this function, some more efficient than others, this works "brute force" so we are only checking up to the square root of the number.

After we have a function that checks if a given number is prime, in this case, verificar_primo(n), we just need to count the number of times that the members of your list are cousins:

def verificar_primo(n): # admitindo que n é natural
  if n == 2 or n == 3: return True
  if n < 2 or n%2 == 0: return False
  if n < 9: return True
  if n%3 == 0: return False
  r = int(n**0.5)
  f = 5
  while f <= r:
    if n%f == 0: return False
    if n%(f+2) == 0: return False
    f += 6
  return True    

a_sua_lista=list(range(1,
contador=0
for i in a_sua_lista:
  if i==int(i) and i>0 and verificar_primo(i): # se i for natural e primo, se tivermos a certeza que i é natural basta escrever: if verificar_primo(i):
    contador+=1

print("Existem %d elementos primos nesta lista." % contador)

Output:

Existem 5 elementos primos nesta lista.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.