The first 100 prime numbers

-1

I have created a code to print the first 100 prime numbers, but the screen is blank.

I know I'm probably not doing it right, I'd like the fix 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++;
        }
    }
}
    
asked by anonymous 05.09.2018 / 19:25

1 answer

1

There are several problems in this logic that I do not even know where to start. Besides the code is too complex. Break the problem down to understand it 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 a function, and so it still avoids using flags that would be necessary without the separation. I started at 2 because 1 is not known to be a cousin.

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

Who is not prime is one that 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 it is not prime and we do not need to keep checking the rest.

If you go through all verification and nothing is divisible, then it 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');
    
05.09.2018 / 19:44