Created
November 13, 2011 18:14
-
-
Save jakedobkin/1362432 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/node | |
//NOW WITH NODE.JS | |
n=2000000; | |
sumPrimes=0; | |
myPrimes = new Array(); | |
// set all array values to true | |
for (i=2;i<=n;i++) | |
{ | |
myPrimes[i]=true; | |
} | |
// sieve of eratosthenes | |
for (i=2;i<=n/2;i++) | |
{ | |
if (myPrimes[i]) | |
{ | |
for (j=2*i;j<=n;j+=i) | |
{ | |
myPrimes[j]=false; | |
} | |
} | |
} | |
// add up unsieved primes | |
for (i=2;i<=n;i++) | |
{ | |
if(myPrimes[i]) | |
{ | |
sumPrimes+=i; | |
} | |
} | |
console.log(sumPrimes); |
Yes- it is smart to use just one loop!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can do this with just your middle loop.
First of all, you don't need to initialize your array. I applaud, it's the good thing to do, but it's not necessary. Before you touch values in the array, myPrimes[anything] is false.
Your sieve implementation was basically exactly like mine.
The n/2 trick is good. I didn't do that.
You don't need a separate loop to add up the primes, you can just accrue the sum as you go along.