What have you tried so far? The community has many many examples of code that does this already 🙂
You don't need the mod() function, you use the simple elimination method:
data primes;
array primes {1000} _temporary_ (1000*1);
do i = 2 to 1000;
if primes{i} then do j = 2 * i to 1000 by i;
primes{j} = 0;
end;
end;
do number = 2 to 1000;
if primes{number} then output;
end;
keep number;
run;
Revised code, made dynamic and optimized:
%let max=1000000;
data primes;
array primes {&max.} _temporary_ (&max.*1);
do i = 2 to int(sqrt(&max.));
if primes{i} then do j = 2 * i to &max. by i;
primes{j} = 0;
end;
end;
do number = 2 to &max.;
if primes{number} then output;
end;
keep number;
run;
I used a million because before that, there was no measurable difference between with and without the sqrt function. With a million, the difference was .06 seconds to .10 seconds in favor of using the function, using UE on a MacBook Pro.
Kurt,
If you make it:
array primes {&max.} _temporary_;
do number = 1 to &max.;
primes{number} = 1;
end;
you will reduce memory by 50%.
All the best
Bart
There seems to be slight tradeoff (the additional do loop added another .01 seconds), but this is a valid point when &max is increased by several orders of magnitude.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Select SAS Training centers are offering in-person courses. View upcoming courses for: