Check which numbers are primes within a vector

Asked

Viewed 81 times

0

I’m having a hard time with this activity:

b) Module that takes as parameter an array of integers and returns the number of primes in the vector. This module should call the function IsPrime of the next question.

c) A module that takes a positive integer as a parameter and returns true if the number is prime or false if the number is not prime. The method NumberOfPrimes should call the method IsPrime.

I’m reading the vector like this:

vetor = []
valor = int(input('Digite o tamanho do vetor: '))

while len(vetor) < valor:
    vetor.append(int(input('Digite um numero: ')))

print('=' * 50)
print("Seu vetor é: {0}".format(vetor))
print('=' * 50)

But when I need to go through each element of the vector, and do a check and tell if it’s prime, it goes wrong.

c = 0
qntPrimo = 0

for elemento in vetor:
    for divisor in range(1, elemento +1):
        if elemento % divisor == 0:
            c = c + 1
    if c == 2:
        qntPrimo += 1
        print(qntPrimo)
  • 1

    "came out wrong", what "comes out"? And what should come out?

  • in the case of item b, it should show a only the amount of a primes within the vector. if I have it rotated the way I put it here, it executes only the part of the vector reading and the entire print.

  • In the calculating part of the cousin it shows nothing on the console.

  • It will only show if there is some prime value. In the vector you tested there was at least one prime number?

  • yes, I’m always putting the values [1, 2, 3, 4, 5] to test

  • The value of c should not restart each element?

  • How so? I use c as a counter of qnts times that element is divided.

  • Not only that... but all of them, in the same variable.

  • I don’t know if I understand or how.

Show 4 more comments

2 answers

0

Your variable c (counting the number of divisors) must be reset to each number being tested. The way you did, she ends up counting the total amount of divisors of all the numbers. Also, you should only print the amount of primes at the end, after you have made the loops:

qntPrimo = 0
for elemento in vetor:
    c = 0 # zerar aqui
    for divisor in range(1, elemento +1):
        if elemento % divisor == 0:
            c = c + 1
    if c == 2:
        qntPrimo += 1

print(qntPrimo) # só imprime a contagem no final

Although the exercise asks to create separate functions: one that only checks if a number is prime, and another that counts the number of primes, using the first function. That is to say:

# verifica se o número é primo
def IsPrime(n):
    if n <= 1: # 0 e 1 não são primos, e estou considerando que os negativos também não são
        return False

    qtd_divisores = 0
    # todo número é divisível por 1 e por ele mesmo, então pra que testá-los? Comece pelo 2 mesmo
    for i in range(2, n):
        if n % i == 0:
            qtd_divisores += 1

    # é primo se a quantidade de divisores é zero
    return qtd_divisores == 0

# retorna a quantidade de números primos
def NumberOfPrimes(numeros):
    qtd_primos = 0
    for n in numeros:
        if IsPrime(n):
            qtd_primos += 1
    return qtd_primos

I changed a little the algorithm that checks if it is prime, since 1 and 0 are not primes, besides not having to check if the number is divisible by 1 and by itself (all are, it is redundant to check this). Of course you can still improve a lot, has better algorithms, but it is not the focus of the question.

Once having the above functions, just use them:

vetor = []
qtd = int(input('Digite o tamanho do vetor: '))
for _ in range(qtd): # outra forma de ler os números
    vetor.append(int(input('Digite um numero: ')))

qtd_primos = NumberOfPrimes(vetor)
print(f'No vetor {vetor} existem {qtd_primos} números primos')

Also note that separating into functions makes it easier to understand what each part of the program does. When trying to do two things with two loops nested, the variables used by each end up getting confused and the code became more confused and difficult to be debugged.

Finally, I also gave better names for variables. It may seem like a silly detail, but give names better help when programming.

-1

Hello, I hope you understand my explanation if we don’t have a dialogue :p

explanation of the loop:
After entering the values (vector size), you have to expand the number , the range function will generate numbers from a range to the specified limit.
typed a 1 position vector and then typed 5 number...range will return the 2,3,4,5 number. first loop is the vector size and the second generates the size informed by vector value.

Below the second is, the if check tests whether the rest of the division of a number by another will be 0(zero) so it is a multiple of the predecessor and is not prime while it was added in the variable called "prime" the result will be multiple and not prime against match if in the interaction of the loops there are no additions in the variable "prime" indicates that the number is prime due the rest of the division is not 0

vetor = []
primo=0
valor = int(input('Digite o tamanho do vetor: '))

while len(vetor) < valor:
    vetor.append(int(input('Digite um numero: ')))

#Os números primos são os números naturais que podem ser divididos por apenas dois fatores: o número um e ele mesmo.
for indice in range(len(vetor)):
   for percorrer in range(2,vetor[indice]):
     if vetor[indice] %  percorrer == 0:
        print("Numeros multiplos", vetor[indice])
        primo+=1
   if primo ==0:
     print("Numero primo",vetor[indice])





print('=' * 50)
print("Seu vetor é: {0}".format(vetor))
print('=' * 50)
  • Hi, good night, I think I understand your code, I’m just not sure what vector[Indice] means, I don’t think I’ve ever seen this syntax before.

  • I thought it was cool about how you used the vector itself to go through the list, I couldn’t format it in any way. I think q was the very syntax q I didn’t understand. type : for x in range(1, vector). so it gave error, but with this Len it makes perfect sense.

  • Len() return the size of the vert. then "for i in range(Len(vector)): when printing "i" returns the positions

  • this vector[Indice]... manually would be something like vertor[0].. or vector[1]... q returns the contents in the vertor at position 0 or 1... the "[Indice]" is the position of the vector.

  • Toppp understood now. Thank you so much!

Browser other questions tagged

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