Reply to comment
How to Print Prime Numbers, a C++ Example
The following code uses the Sieve of Eratosthenes method to print all prime numbers in the range of 2 to n, while n being the upper limit, command line integer you feed into the program. You could also just hard code n if you wanted to. Since it's in C++, this code can easily be ported to PHP or other languages that share similar syntax.
int main(int argc, char *argv[]) { int n; n = atoi(argv[1]); int myarray[n]; // populate the array for(int i=0, j=2; j<=n; i++, j++) { myarray[i] = j; } // mark the multiples with 1's for(int i=2; i<=n; i++) { // run through each number, 2 through n for(int j=0; j<(n-1); j++) { // run through each element of your array if(myarray[j]>1 && myarray[j]!=i && myarray[j]%i==0) { myarray[j] = 1; // mark the multiple } } } // print out the elements that don't have 1's for(int i=0; i<(n-1); i++) { if(myarray[i] != 1) { printf("%d ", myarray[i]); } } return 1; }
