Advertisement
EmanueleBonin

Crivello ottimizzato di Eratostene con calcolo pi

Jul 10th, 2019
562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3.  
  4. #define RANGE 10000u
  5. #define SCMAX (RANGE/3)
  6. // compiled with cl65  -r -O -Cl crivello.c -o crivello.prg
  7. typedef unsigned char uint_8;
  8.  
  9. uint_8 composite[RANGE];
  10.  
  11.  
  12. int main(void) {
  13.     clock_t Ticks, TicksDelta;
  14.     unsigned int Sec;
  15.     unsigned int Milli;
  16.  
  17.     unsigned int pi=0;
  18.     unsigned int pr=0;
  19.     register unsigned int i;
  20.     register unsigned int j=2;
  21.     register unsigned int ScopeMax;
  22.  
  23.     for(j=0,i=1; j<RANGE; ++j) {
  24.         composite[j]=0;
  25.         composite[i]=1;
  26.         ++j;
  27.         i+=2;
  28.     }
  29.     j=3;
  30.     ScopeMax    = RANGE/j;
  31.  
  32.     printf("\nPress enter to start\n");
  33.     //getchar();
  34.     printf("\nComputing...\n");
  35.     Ticks = clock();
  36.     while(j<SCMAX) {
  37.         pr=j+j+j-1;
  38.         for (i=3; i<=ScopeMax; i+=2) {
  39.             composite[pr]=1;
  40.                 pr+=j+j;
  41.         }
  42.         j+=2;
  43.         ScopeMax=RANGE/j;
  44.     }
  45.     TicksDelta = clock() - Ticks;
  46.     Sec = (unsigned short) (TicksDelta / CLOCKS_PER_SEC);
  47.     Milli = ((TicksDelta % CLOCKS_PER_SEC) * 1000) / CLOCKS_PER_SEC;
  48.     printf ("Time used: %u.%03u seconds = %u ticks\n", Sec, Milli, (unsigned short) TicksDelta);
  49.  
  50.     printf("Press enter to print the prime numbers\n");
  51.     getchar();
  52.     printf("\n");
  53.     composite[0]=1;
  54.     composite[1]=0;
  55.     for(i=0; i<RANGE; ++i) {
  56.         if(composite[i]==0) {
  57.             ++pi;
  58.             printf(" %u ", i+1);
  59.         }
  60.     }
  61.     printf("\nPi = %u", pi);
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement