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.

  1. int main(int argc, char *argv[]) {
  2.  
  3. int n;
  4. n = atoi(argv[1]);
  5.  
  6. int myarray[n];
  7.  
  8. // populate the array
  9. for(int i=0, j=2; j<=n; i++, j++) {
  10. myarray[i] = j;
  11. }
  12.  
  13. // mark the multiples with 1's
  14. for(int i=2; i<=n; i++) { // run through each number, 2 through n
  15. for(int j=0; j<(n-1); j++) { // run through each element of your array
  16. if(myarray[j]>1 && myarray[j]!=i && myarray[j]%i==0) {
  17. myarray[j] = 1; // mark the multiple
  18. }
  19. }
  20. }
  21.  
  22. // print out the elements that don't have 1's
  23. for(int i=0; i<(n-1); i++) {
  24. if(myarray[i] != 1) {
  25. printf("%d ", myarray[i]);
  26. }
  27. }
  28.  
  29. return 1;
  30. }

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.