Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 15 of 23
Thread: Finding prime numbers code issue

06262013, 01:55 AM #1
 Join Date
 Jun 2013
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Finding prime numbers code issue
I'm a beginner in JS and can't figure out why this isn't working right.
It prints out "2,2,2,2,2,2,2" and so on, but I need it to print the first 100 prime numbers.
Any help is appreciated.
Code:var primeNumbers = []; //Prime numbers stored here while(primeNumbers.length <= 100){ //Number to be tested if it is a prime. var candidate = 2; for(var i = 2; primeNumbers.length <= 100; i++) { if(candidate % i == 0){ continue; }else{ i = 0; primeNumbers.push(candidate); } }; candidate++; }; for(var print = 0; print <= primeNumbers.length; print++){ //Prints out the prime #'s stored in var primeNumbers. console.log(primeNumbers[i] + ","); };
06262013, 02:31 AM
#2
Code:for(var print = 0; print <= primeNumbers.length; print++){ //Prints out the prime #'s stored in var primeNumbers. console.log(primeNumbers[i] + ","); };
Be yourself. No one else is as qualified.
06262013, 02:32 AM
#3
But the algorithm you are using still won't work.
It's horribly broken.
Last edited by Old Pedant; 06262013 at 02:36 AM.
Be yourself. No one else is as qualified.
06262013, 02:42 AM
#4
 Join Date
 Jun 2013
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Thank you, i didn't catch that, but it is still printing 2 over and over.
For a more efficient way to find primes, do you mean the Sieve of Eratosthenes?
06262013, 03:27 AM
#5
 Join Date
 Jun 2013
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Reading this article http://en.wikipedia.org/wiki/Primali...#Naive_methods
Changed it a bit, although still bad and broken..
Code:var primeNumbers = []; //Prime numbers stored here while(primeNumbers.length <= 100){ //Number to be tested if it is a prime. var candidate = 2; for(var i = 2; i <= Math.sqrt(candidate); i++) { if(candidate % i === 0){ continue; }else{ primeNumbers.push(candidate); i = 2; } }; candidate++; }; var output = primeNumbers.join(); //Combines array into string and prints it. console.log(output);
06262013, 04:06 AM
#6
The Sieve is the most efficient that I know of.
But even one like yours can be improved twofold by just considering odd numbers.
Just push 2 into the array and then start with 3.
Be yourself. No one else is as qualified.
06262013, 04:26 AM
#7
But even better: Why try moduloing the candidate with *every* number (even every odd number)?? Why not just try testing it against ALL THE PRIMES LESS THAN itself!
Code:<script type="text/javsascript"> // Prime numbers stored here // ..start with 2 as only even prime var primeNumbers = [2]; var candidate = 3; // start with first odd number while ( primeNumbers.length < 100 ) { var prime = true; // assume candidate is prime // no point in checking against primeNumbers[0], // which is 2. Because our candidate value will // never be even...so start at element 1 of the array instead for ( var i = 1; i < primeNumbers.length; ++i ) { if ( candidate % primeNumbers[i] == 0) { prime = false; break; // no point in continuint } } if ( prime ) primeNumbers.push(candidate); candidate += 2; // skip the even numbers }; alert( primeNumbers ); </script>
Be yourself. No one else is as qualified.
Users who have thanked Old Pedant for this post:
Devin_p (06262013)
06262013, 04:49 AM
#8
Even getting all the prime numbers less than 1000, the Sieve method is roughly 3 times faster than the method shown above. I would expect its advantage to grow as the number of prime numbers desired grows.
EDIT: I couldn't stand it; had to test my gut feelings.
Yes, if you ask for all prime numbers less than 5000, then the Sieve outperforms the modulo by a factor of *TEN*.
Not surprising, but I just wanted to check my sanity.
Last edited by Old Pedant; 06262013 at 04:52 AM.
Be yourself. No one else is as qualified.
06262013, 05:51 AM
#9
 Join Date
 Jun 2013
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Thank you for all your help and effort you put into this!
06262013, 05:58 PM
#10
Just for completeness, here's the version of the Seive of Erastothenes that I used:
There are ways to make that a little more efficient, but not enormously so.Code:<script type="text/javascript"> var nums = [ ]; var primes = [ ]; var MAXNUM = 5000; // change this as desired for ( var n = 0; n < MAXNUM; ++n ) { nums[n] = n; } // run the actual seive for ( var chk = 2; chk < MAXNUM; ++chk ) { if ( nums[chk] != 0 ) { primes.push(chk); for ( var mark = chk; mark < MAXNUM; mark+=chk ) { nums[mark] = 0; } } } alert(primes); </script>
Be yourself. No one else is as qualified.
06262013, 06:30 PM
#11
 Join Date
 Jan 2013
 Location
 Germany
 Posts
 578
 Thanks
 4
 Thanked 77 Times in 77 Posts
Warning: Some math up ahead.
Even better: Only try all integers less than or equal to the square root of the number [1][2] And now combining these two solutions, even better is to check all prime numbers less than or equal to the number [3].
As for algorithms in general: First off, the Sieve of Eratosthenes could be improved, but one could also use another optimized version known as the Sieve of Atkin which is better by a factor of 1/(log log n).
[1] If p was not prime, it could be factored into p = ab. Without loss of generality, assume a > sqrt(p). It would immediately follow that b < sqrt(p). Since finding only one factor suffices to disprove that p is a prime, it is enough to check all integers less than or equal to the square root of the number in question.
[2] The number of primes <= x is asymptotically equivalent to x/ln(x). The limit of that divided by sqrt(x) is  as one can see with fairly basic maths  infinite, which means that it is by far better to use sqrt(x). As an additional benefit the test is independent of all prime numbers smaller than the number in question.
[3] Again, if p was not prime, there would be a factorization p = ab. In [1] we have seen that we can assume a <= sqrt(p). Now, if a was not prime itself, it could be further factorized into a = xy. The same argument would show (without loss of generality) that x <= a <= sqrt(p).
06262013, 06:38 PM
#12
 Join Date
 Sep 2010
 Posts
 2,451
 Thanks
 17
 Thanked 275 Times in 275 Posts
Welcome to http://www.myphotowizard.net
where you can edit images, make a photo calendar, add text to images, and do much more.
When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.
06262013, 07:52 PM
#13
Well, even the version of the Sieve of Erastothenes that I used is not the best, as I said. I know it can easily be made about 4 times as efficient. But that code is pretty simple and compact, and unless you are going for a huge number of primes it's more than adequate.
Be yourself. No one else is as qualified.
06272013, 07:10 AM
#14
 Join Date
 Jan 2013
 Location
 Germany
 Posts
 578
 Thanks
 4
 Thanked 77 Times in 77 Posts
@DrDos
Less than or equal to(!)  this is crucial, otherwise you would count every square of a prime number as prime.
@OldPedant
I agree that there is no need to improve it if it satisfies your needs. But switching to the square root is not a factor of four, we're talking orders of magnitude and a legit asymptotic benefit here. It's not a very special improvement either, it's fairly common to write even simple implementations using the square root as the bound. So yes, for the first few hundred primes it should be practically irrelevant, but I believe that with technical algorithms like this, at least showing what impact little details can have is important.
06272013, 06:41 PM
#15
Okay, I give up. How does using the square root of the number being checked apply to the Sieve of Erastothenes algorithm???
Look at my code in post #19.
To do the prime.push(chk), we must loop all the way to the max num we are wanting to check.
And then the inner loop must also go all the way to that same max num to be sure all the multiples of the given prime are marked.
But notice that the marking loop at least only starts at the found prime number, so it's not terrible. But we could get 4 times as efficient by only considering odd numbers and by not bother with marking even multiples of a prime number. Oh, and we don't need to mark the prime number we just found.
Further than that...I dunno. What do you think can be done? And how does square root apply to this algorithm??
Be yourself. No one else is as qualified.