Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find prime numbers between 0 - 100?

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()); 
like image 928
user1599757 Avatar asked Aug 15 '12 08:08

user1599757


People also ask

What is the trick to finding prime numbers?

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).

How do you find prime numbers from 0 to 50?

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.


1 Answers

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.

like image 79
Ted Hopp Avatar answered Oct 07 '22 21:10

Ted Hopp