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.
You realize that in the first line of your
for
you evendiv
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 fromconsole.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. Useconsole.log()
to see all numbers on the console.– Máttheus Spoo
Elaborate better on what "not working" means. Do you have an error message? Shows nothing? Enters infinite loop?
– fernandosavio
Possible duplicate of Function to check if number is prime in Javascript
– hkotsubo