prime.gms : Prime Number Generation
This example shows how to use a WHILE statement to find a set
of prime numbers.
Reference:
- GAMS Development Corporation, Formulation and Language Example.
Small Model of Type: GAMS
$title Prime Number Generation (PRIME,SEQ=157)
$eolcom !
$Ontext
This example shows how to use a WHILE statement to find a set
of prime numbers.
GAMS Development Corporation, Formulation and Language Example.
$Offtext
sets s set of prime numbers / 1*200 / , ss(s) primes found until now
scalars more temporary flag
candidate prime candidate
parameter ps(s) first s prime numbers;
ps(s) = 0; ! clear prime array
ss(s) = no; ! make primes found set empty
candidate = 3; ! set prime to get started
loop(s,
more = 1; ! turn on the search
while(more, ! seacrh until found
loop (ss$more, ! only test if still a candidate
more = mod(candidate,ps(ss)) ) ! a prime must have a remainder
if(more, ! check if we got one
ss(s) = yes; ! bump set of found primes
ps(s) = candidate ); ! save prime number
more = not more; ! flip the search flag
candidate = candidate + 2 ) ); ! next candidate has to be odd
display ps ;