The first 100 prime numbers

Asked

Viewed 1,612 times

-1

I created a code to print on the screen the first 100 primes, but the screen is blank.

I know that I am probably not doing the best way, I would like the correction of this and the best way to solve the problem, if possible.

var dividendo, div, soma;
for(dividendo=1;(dividendo>0)&&(dividendo<100);dividendo++){
    div=1;
    soma=0;
    while(dividendo>=div){
        if((dividendo/div==1)||(dividendo/div==dividendo)){
            soma=soma+1;
            if((soma=1)||(soma=2)){
                document.write(dividendo);
            }
            div++;
        }
    }
}
  • 4

    You realize that in the first line of your foryou even div a 1 and whenever the loop again executes it equals again? div will be 1 eternally so. Otherwise, what would be (dividendo/div==1) ? Something else: document.write is different from console.log, the first command will leave your screen all white and write what you said. If you run again, it will delete the old and replace the new value. Use console.log() to see all numbers on the console.

  • 3

    Elaborate better on what "not working" means. Do you have an error message? Shows nothing? Enters infinite loop?

1 answer

2


There are several problems in this logic that I don’t even know where to start. Besides the code is too complex. Divide the problem to understand easier.

The basic logic is to count to 99 (as it was in the code) to test all the numbers you want, that’s one thing. The logic that tests whether it is prime or not is something else and the ideal is already to be a function, and so still avoid using flags that would be necessary without separation. I started with 2 because 1 is not known to be a cousin.

In the test you have to test from the 2 because divisible by 1 everything is. And goes up to the number previous to the one you are testing, every number is divisible by itself, being prime or not.

Who is not prime is the one who is divisible by some other number that is not only 1 or himself. So any situation that the rest of the division equals zero we already know that he is not cousin and we no longer need to keep checking the rest.

If you go through all the checks and nothing is divisible then yes he is cousin.

function ehPrimo(i) {
    for (var divisor = 2; divisor < i; divisor++) if (i % divisor == 0) return false;
    return true;
}

for (var i = 2; i < 100; i++) if (ehPrimo(i)) document.write(i + '\n');

I put in the Github for future reference.

Browser other questions tagged

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