Divisible - Portugol (VISUALG)

Asked

Viewed 4,559 times

2

I have the following question and below what I have tried but it is not just showing the divisible numbers that is my intention.

I’m doing the test by typing the number 8, the correct one was for the program to say "8 is divisible by 8 and 2"

Write an algorithm that takes a keyboard number and tells you if it is divisible by 8, by 5, by 2 or if it is not divisible by any of these. Check for each of the numbers. Example: Number: 8 Divisible by 8

My Code

var 
numero,contador,divisivel: inteiro
inicio
 contador <- 1
 divisível<- 0
escreva("Digite um número: )
 leia(numero)
repita
 escreva(contador)
   se(numero % contador = 0) então
  divisível <- divisível + 1
fimse
  contador <- contador + 1
ate (contador > numero)
  escreva("Número: ",divisível)
fimalgoritimo
  • Can you format your code better? , so you don’t need the image to understand it?

  • 1

    @Jeffersonquesado I could not leave as in the image. :( I’m new at stackoverflow. If you can help me in formatting the code I would really appreciate it. :)

  • In the problem it only asks to test the divisibility by 2, 5 and 8, but you did the test to count how many divisors have a number; you did more than the problem asked

  • while I write the answer, you can take a look at the tour. There is also a section in the help center about markup language

  • 1

    @Jeffersonquesado and how would be the correct code for divisibility only by 2,5 and 8?

  • I just answered; on mobile, my typing is slower

  • 1

    Thank you and sorry! I’ll see now. Thank you very much!!

Show 2 more comments

1 answer

5


As I don’t know the exact syntax of portugol/visualg, please correct any slip

This is a problem whose answer needs to meet a decision question and also needs to meet the formatting of an answer.

What is a matter of decision?

A question of decision is a problem to which one must answer sim or não. Examples of decision problem:

Note that it is not always possible to get the affirmative or negative answer, but this is another conversation for another day.

Problem of decision of the matter

The question asks if a given number is divisible by 8, if it is divisible by 5 and by 2; ask this individually, then, for 200, I need to answer yes three times.

Each of these questions is an instance of a larger problem: X is divisible by Y?

To answer the general question, the code is:

X % Y = 0

So, for each of the questions, I replace the Y at the appropriate value:

X % 8 = 0
X % 5 = 0
X % 2 = 0

Formatting the answer

The format of the answer is:

X é divisível por N( e por K)*

Where X is the number given, N is the first divisor, and the part in parentheses repeats for each K also divider of X.

To identify whether dividers have already been detected in our search universe (8, 5, and 2, in that order), I will use a variable called divisores_encontrados, that will store the value of how many dividers the algorithm has found up to that instant. This means that it starts with zero and, if any of the checks returns that the number is divisor, I increment the value of divisores_encontrados.

Note: consider everything after the # as a comment

var entrada, divisores_encontrados, divisor_teste: inteiro
início 
    divisores_encontrados <- 0 # inicializando o valor; ainda não foi encontrado nada
    leia(entrada)

    divisor_teste <- 8
    se entrada % divisor_teste = 0 então 
        se divisores_encontrados = 0 # primeira vez que encontrou um divisor 
            escreva(entrada)
            escreva(" é divisível por ")
            escreva(divisor_teste)
        senão
            escreva(" e por ")
            escreva(divisor_teste)
        fimse # verificação do primeiro divisor encontrado
        divisores_encontrados <- divisores_encontrados + 1
    fimse # verificação da divisibilidade 

    divisor_teste <- 5
    se entrada % divisor_teste = 0 então 
        se divisores_encontrados = 0 # primeira vez que encontrou um divisor 
            escreva(entrada)
            escreva(" é divisível por ")
            escreva(divisor_teste)
        senão
            escreva(" e por ")
            escreva(divisor_teste)
        fimse # verificação do primeiro divisor encontrado
        divisores_encontrados <- divisores_encontrados + 1
    fimse # verificação da divisibilidade 

    divisor_teste <- 2
    se entrada % divisor_teste = 0 então 
        se divisores_encontrados = 0 # primeira vez que encontrou um divisor 
            escreva(entrada)
            escreva(" é divisível por ")
            escreva(divisor_teste)
        senão
            escreva(" e por ")
            escreva(divisor_teste)
        fimse # verificação do primeiro divisor encontrado
        divisores_encontrados <- divisores_encontrados + 1
    fimse # verificação da divisibilidade 

    se divisores_encontrados = 0 
        escreva(entrada)
        escreva(" não é divisível por 2, 5 e nem 8")
    fimse # caso sem divisibilidade por 2, 5, 8

    escreval("") # só para pular linha no fim ;-)
fimalgoritmo

Bonus: About the amount of divisors

Your question program calculates how many divisors a number has. It writes at each loop step which number being tested, but without breaking line.

You can just not write down these intermediate numbers if they don’t interest you.

To know how many divisors a number has, we also don’t need to go through all the numbers smaller than the number given; there are decomposition strategies in prime numbers and, also, one that allows you to count to the square root of the number. I’ll go into more detail on that last one.

Every number X % Y = 0 means that there is F whole such that F * Y = X. For any number other than the perfect square root of X, find Y means knowing the existence of your brother factor F. If I assume that Y is less than F, then I just need to count how many Ydifferent s exist in the range [1, raiz(X)) (left the interval open at the square root, then explain why) and multiply by 2. In the case of the square root, if the number found is a perfect square, the pair of raiz(X) will be F = raiz(X), then that particular number can only enter once.

The case of the number 1 and of X are trivial dividers, so I won’t even go through them in the loop

var divisores_encontrados, r, entrada, divisor_teste: inteiro
início
    leia(entrada)

    se entrada = 1 # único caso que existem menos de dois divisores
        divisores_encontrados = 1
    senão
        divisores_encontrados <- 2 # os dois triviais
         r <- arredonda_baixo(raiz(entrada))
         divisor_teste <- 2
         enquanto divisor_teste < r # não pode ser <= porque o intervalo é aberto na raiz
             se entrada % divisor_teste = 0
                 divisores_encontrados <- divisores_encontrados + 2 # lembrando que achamos divisor_teste e sabemos que ele tem um par F maior do que a raiz quadrada
             fimse
             divisor_teste <- divisor_teste + 1
          fimenquanto

          se entrada % r = 0
             divisores_encontrados <- divisores_encontrados + 1 # entrada é quadrado perfeito
        fimse
    fimse

    escreva(entrada)
    escreva(" possui ")
    escreva(divisores_encontrados)
    escreval(" divisores")
fimalgoritmo
  • 1

    Thank you very much for the explanations, they were of paramount importance. Tomorrow I will test the code more calmly and give a feedback if it worked. hug and success!

  • 1

    Excellent answer! Helped in my question!

Browser other questions tagged

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