Online File

How to use this page


Rick Aster: Professional SAS Programming Shortcuts: Contents

Chapter 88
Program
Prime number sieve


%LET TOTAL = 2000; * Limits the number of prime numbers generated ;
%LET DIM = 1000; * The size of the sieve arrays used ;
%LET TIME = 30; * Time limit in seconds ;

data _null_;
   array p{&DIM.} _temporary_; * Prime numbers;
   array m{&DIM.} _temporary_; * Multiples of prime numbers;
   timeout = datetime() + &TIME.; * Time limit;
   file print notitles;
   square = 4;

   do x = 2 to constant('exactint'); * Is X prime? ;
      if datetime() >= timeout then stop; * Time limit reached ;
      if x = square then do; * Extend sieve;
         imax + 1;
         if imax >= &DIM. then stop; * Sieve size limit reached. ;
         square = m{imax + 1}; 
         continue;
         end;
      * Find least prime factor (LPF). ;
      lpf = 0;
      do i = 1 to imax until (lpf);
         do while (m{i} < x); * Update sieve with new multiple. ;
            m{i} + p{i};
            end;
         if m{i} = x then lpf = p{i};
         end;
      if lpf then continue; * Composite number found. ;
      put x @; * Write prime number in output. ;
      n + 1;
      if n >= &TOTAL. then stop; * Output maximum reached. ;
      else if n <= &DIM. then do; * Add prime number to sieve. ;
         p{n} = x;
         m{n} = x*x;
         end;
      end;
   stop;
run;

 O /\

Global
Statements

RICK ASTER

SAS

BOOKS

Tech | Dictionary

Download | Rastinate

Rick Aster

Professional SAS Programming Shortcuts

Contents/Online Files

Corrections

Catalog Page