home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / cc65v261.zip / cc65.zip / samples / sieve.c < prev   
C/C++ Source or Header  |  2000-12-18  |  1KB  |  68 lines

  1. /*
  2.  * Calculate all primes up to a specific number.
  3.  */
  4.  
  5.  
  6.  
  7. #include <stdio.h>
  8. #include <conio.h>
  9.  
  10.  
  11.  
  12. /*****************************************************************************/
  13. /*                                      Data                     */
  14. /*****************************************************************************/
  15.  
  16.  
  17.  
  18. #define COUNT        8192        /* Up to what number? */
  19. #define SQRT_COUNT    91        /* Sqrt of COUNT */
  20.  
  21. static unsigned char Sieve[COUNT];
  22.  
  23.  
  24.  
  25. /*****************************************************************************/
  26. /*                                      Code                     */
  27. /*****************************************************************************/
  28.  
  29.  
  30.  
  31. int main (void)
  32. {
  33.     /* This is an example where register variables make sense */
  34.     register unsigned char* S;
  35.     register unsigned         I;
  36.     register unsigned         J;
  37.  
  38.     /* Execute the sieve */
  39.     I = 2;
  40.     while (I < SQRT_COUNT) {
  41.     if (Sieve[I] == 0) {
  42.         /* Prime number - mark multiples */
  43.         S = &Sieve[J = I*2];
  44.                while (J < COUNT) {
  45.               *S = 1;
  46.               S += I;
  47.               J += I;
  48.         }
  49.     }
  50.     ++I;
  51.     }
  52.  
  53.     /* Print the result */
  54.     for (I = 2; I < COUNT; ++I) {
  55.     if (Sieve[I] == 0) {
  56.         printf ("%4d\n", I);
  57.     }
  58.     if (kbhit() && cgetc() == 'q') {
  59.         break;
  60.     }
  61.     }
  62.  
  63.     return 0;
  64. }
  65.  
  66.  
  67.  
  68.