{ Copyright (c) 1995 by Albert van der Horst } program pi; uses Crt; { This program calculates how many primes there are less or equal a given number. This function is called pi(n). It only demonstrates the algorithm. The range allowed for the number `n' is limited by the signed integers Pascal can handle: 32675. It is based on a careful analysis of the Eratosthenes' sieve. In the sieve numbers are dismissed because they are divisible by prime numbers. We will use the notion of "dismissing by". A number is "dismissed by" a prime, if that prime is its smallest divider. The numbers smaller than or equal to `n' are divided in disjunct sets of numbers dismissed by a certain prime, and the number 1. A large primes p<=n (in fact all primes larger than sqrt(n)) form such a set with only one member. (The definition implies that a prime is dismissed by itself.) An example of the numbers <=17 and their dismissing primes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 - 2 3 2 5 2 7 2 3 2 11 2 13 2 3 2 17 By inspection we see that Dismiss(17,3) should return 3. } { IsPrime is an auxiliary function that tells whether `n' is prime. } Function IsPrime( n: integer):boolean; var i: integer; { Just a counter } begin IsPrime := True; if n>=4 then for i:=2 to n do if n/in then begin CountPr := r; exit end else if IsPrime(p) then begin r := r - DismissedBy( n, p ); r := r+1; { Correct: the prime itself was also dismissed } end; CountPr := r; end; var N : integer; begin {countpr} repeat Writeln('Give a number ...'); read(N); Writeln('The number of primes <=',N,' is ', CountPr(N) ); until N=0; end.