algorithm not doing the necessary checks

Asked

Viewed 35 times

0

hello, I have to make an algorithm in visualg where you have to read from the keyboard a positive integer value and show on the screen all primes smaller than the number read from the keyboard, however, is being shown only the value typed if it is prime, below follows what I did:

Algorithm "without name"

Var
cont , x, v1, aux: inteiro


Inicio
escreval ("digite um valor")
leia (v1)
aux<-v1
repita
      para x de 1 ate aux faca
           se (v1%x=0) entao
              cont<-cont+1
           fimse
      fimpara
      se (cont=2) entao
         escreval (v1)
      fimse
      v1<-v1-1
ate (v1<0)

Fimalgoritmo

2 answers

0

Since any number is always divisible by 1 and by itself, for the number to be prime it is sufficient to have no other divisor.

Algoritmo "semnome"
Var
    cont, cont2 , x, v1, aux: inteiro
Inicio
    escreval ("digite um valor")
    leia (v1)
    aux<-v1
    repita
        cont2 <- 0
        para x de 2 ate aux-1 faca
            se (v1%x=0) entao
                cont2 <-cont2 + 1
            fimse
        fimpara
        se (cont2=0) entao
            escreval (v1)
        fimse
        v1 <- v1 - 1
    ate (v1<=0)
Fimalgoritmo

To optimize a little more you can do:

        para x de 2 ate aux\2 faca

0

You have not set any value for x so it has by default the value 0, look at the condition "if v1 mod x is equal to 0", there is a division by zero. To check if it is prime, the number must be divided by 1 or itself.

Browser other questions tagged

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