Initializing help system before first use

Prime numbers using the Sieve of Eratosthenes


Type: Programming
Rating: 3 (intermediate)
Description: This example calculat all prime numbers between 2 and a given upper bound shows the following features:
  • working with sets
  • nested loops: repeat-until, while, while-do
Algorithm 'Sieve of Eratosthenes': Starting with the smallest one, the algorithm takes every element of a set of numbers SNumbers (positive numbers between 2 and some upper limit that may be specified when running the model), adds it to the set of prime numbers SPrime and removes the number and all its multiples from the set SNumbers.
File(s): prime.mos


prime.mos
(!*******************************************************
  * Mosel Example Problems                              *
  * ======================                              *
  *                                                     *
  * file prime.mos                                      *
  * ``````````````                                      *
  * Example for the use of the Mosel language           *
  * (Calculation of prime numbers)                      *
  *                                                     *
  * Implements the Sieve of Eratosthenes: each time a   *
  * prime number is found all of its multiples are      *
  * deleted from the set of remaining numbers.          *
  *                                                     *
  * (c) 2008 Fair Isaac Corporation                     *
  *     author: S. Heipcke, 2001                        *
  *******************************************************!)

model Prime                    ! Start a new model

parameters
 LIMIT=100                     ! Search for prime numbers in 2..LIMIT
end-parameters

declarations
 SNumbers: set of integer      ! Set of numbers to be checked
 SPrime: set of integer        ! Set of prime numbers
end-declarations

 SNumbers:={2..LIMIT} 
 
 writeln("Prime numbers between 2 and ", LIMIT, ":")

 n:=2
 repeat
   while (not(n in SNumbers)) n+=1
   SPrime += {n}
   i:=n
   while (i<=LIMIT) do
     SNumbers-= {i}
     i+=n
   end-do
 until SNumbers={}    

 writeln(SPrime)
 
end-model

© 2001-2024 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation (“FICO”). Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software described in this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO affiliate). Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use is permitted.