Perfect numbers

Asked

Viewed 1,405 times

3

algoritmo "numeros_perfeitos"
var
c, n:inteiro
nv, np, npv:real
inicio
para n <- 1 ate 100 faca
  para c <- 1 ate n faca
     se n % c = 0 entao
        nv <- n / c
        se nv < n entao
           np <- nv + np
        fimse
     fimse
  fimpara
  se np = n entao
     escreva(np)
  fimse
  np <- 0
  nv <- 0
fimpara
fimalgoritmo

I wrote this code for this exercise:

Write an algorithm that generates and writes the first 4 numbers perfect. A perfect number is one that is equal to the sum of its divisors. Ex: 6 = 1+2+3; 28= 1+2+4+7+14.

But he hangs how much I put from n to 10000 I did something wrong? And why does he perform many cycles in the internal structure (I think it is 100000 cycles)? My logic was bad?

2 answers

4


It is probably taking a long time to execute, as it will perform summation of 1 -> n. That is, for a case where N = 10000, it performs 50005000 times that your cycle. So he hangs, exactly, because it takes time to perform this amount of loops. Some ways you can improve this algorithm are:

  • Whenever you find the perfect fourth number, interrupt the execution of the loop: make a check if 4 numbers were found, if yes, use the interrupt command in the outermost loop

  • You do not need to run the innermost loop from 1 to n, but rather from 2 to n 1/2: First 1 will always divide a number, so instead of starting its sum with 0, you can start with 1. Second multiplication is a complementary operation, then if you know one of the factors, you will know both (in case of multiplication of only 2 terms), it means that you do not need to discover ALL the divisors of N, but only HALF of them, for that, you take the square root of that number. Once this is done, you have to add the two factors to your account, adding C and N/C, when N%C = 0.

  • Thank you very much I understood, it is normal to make this mistake and I was very stupid?

  • It’s part of learning, the important thing is to always try to grow. (:

  • Thanks for the help.

-3

Hope it helps. Code made with java script:

function numeroPerfeito(n) {
  let sum = 0;

  for (let x = 1; x <= (n / 2); x++) {
    if (!(n % x)) {
      sum += x;
    }
  }

  return sum == n;
}
  • The question was not asked and was not asked in [tag:javascript] or other language other than [tag:visualg]. Read [Annaswer] and take our [tour].

Browser other questions tagged

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