brainuser5705

sieve of eratosthenes prime number

Apr 24th, 2021 (edited)
98
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. int main (void)
  3. {
  4.     printf("SIEVE OF ERATOSTHENES ALGORITHM\n");
  5.  
  6.     int num;
  7.     printf("Give a number: ");
  8.     scanf("%i", &num);
  9.     printf("\nTo Display All Prime Numbers Between 1 and %i\n", num);
  10.  
  11.     int P[num];
  12.  
  13.     // initialize array to all zeros
  14.     for (int i = 2; i < num; i++){
  15.         P[i] = 0;
  16.     }
  17.  
  18.     int i = 2;
  19.     while(i < num){
  20.         // 0 value indicates it is not marked as prime
  21.         if (P[i] == 0){
  22.             printf("%i ", i);
  23.         }
  24.         // set multiples of i to 1
  25.         for (int j = 1; i * j <= num; j++){
  26.             P[i*j] = 1;
  27.         }
  28.         // increment for next number to test
  29.         i++;
  30.     }
  31.  
  32.     return 0;
  33. }
RAW Paste Data Copied