In Javascript how would i find prime numbers between 0 - 100? i have thought about it, and i am not sure how to find them. i thought about doing x % x but i found the obvious problem with that. this is what i have so far: but unfortunately it is the worst code ever.
var prime = function (){ var num; for (num = 0; num < 101; num++){ if (num % 2 === 0){ break; } else if (num % 3 === 0){ break; } else if (num % 4=== 0){ break; } else if (num % 5 === 0){ break; } else if (num % 6 === 0){ break; } else if (num % 7 === 0){ break; } else if (num % 8 === 0){ break; } else if (num % 9 === 0){ break; } else if (num % 10 === 0){ break; } else if (num % 11 === 0){ break; } else if (num % 12 === 0){ break; } else { return num; } } }; console.log(prime());
To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).
Calculation: Prime numbers between 0 and 50 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 and 47. So there are total of 15 prime numbers between 0 and 50. ∴ Option 2 is the correct answer.
Here's an example of a sieve implementation in JavaScript:
function getPrimes(max) { var sieve = [], i, j, primes = []; for (i = 2; i <= max; ++i) { if (!sieve[i]) { // i has not been marked -- it is prime primes.push(i); for (j = i << 1; j <= max; j += i) { sieve[j] = true; } } } return primes; }
Then getPrimes(100)
will return an array of all primes between 2 and 100 (inclusive). Of course, due to memory constraints, you can't use this with large arguments.
A Java implementation would look very similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With