PROGRAM PCA$PRIMES C This program generates all the prime numbers in a given integer C range. Prime numbers are placed in PRIMES_TABLE as they are C generated. After being verified, these prime numbers are written C out to a text file PRIMES.DAT. C INTEGER LOW,HIGH,COUNT,ERROR_COUNT,PRIMES_TABLE LOGICAL PRIME DIMENSION PRIMES_TABLE(10000) C Read in the desired integer range from a file and range-check it. C CALL READ_RANGE(LOW, HIGH) LOW = MAX (1, LOW) HIGH = MIN (HIGH, 10000) HIGH = MAX (LOW, HIGH) C Generate all prime numbers in the given range. C COUNT = 0 DO 10 I = LOW, HIGH IF (PRIME(I)) THEN COUNT = COUNT + 1 PRIMES_TABLE (COUNT) = I END IF 10 CONTINUE C Verify that the numbers in PRIMES_TABLE really are prime. C ERROR_COUNT = 0 DO 20 I = 1, COUNT IF (.NOT. PRIME(PRIMES_TABLE(I))) THEN ERROR_COUNT = ERROR_COUNT + 1 END IF 20 CONTINUE IF (ERROR_COUNT .NE. 0) THEN TYPE 30, ERROR_COUNT 30 FORMAT (I5, ' wrong prime numbers generated') END IF C Write the prime numbers out to PRIMES.DAT and type summary data C on the terminal. C CALL OUTPUT_TO_DATAFILE(PRIMES_TABLE, COUNT) TYPE 40,COUNT,LOW,HIGH 40 FORMAT(I5, ' prime numbers generated between', I5, ' and', I5) STOP END C Function to identify whether a given number is prime or not. C If it is prime, the returned function value is TRUE. C LOGICAL FUNCTION PRIME(NUMBER) PRIME = .TRUE. DO 10 I = 2, NUMBER/2 IF ((NUMBER - ((NUMBER / I) * I)) .EQ. 0) THEN PRIME = .FALSE. RETURN ENDIF 10 CONTINUE RETURN END C Subroutine to read in the integer range in which primes are to C be found. C SUBROUTINE READ_RANGE(LOW, HIGH) INTEGER LOW, HIGH OPEN(UNIT=1, FILE='PRIMESIN.DAT', STATUS='OLD') READ(1,100,END=110,ERR=120) LOW, HIGH 100 FORMAT(2I5) CLOSE(UNIT=1) RETURN 110 CALL READ_END_OF_FILE RETURN 120 CALL READ_ERROR RETURN END C Subroutine to print an error message for a read end-of-file. C SUBROUTINE READ_END_OF_FILE TYPE 150 150 FORMAT(' Unexpected end-of-file reading input file') RETURN END C Subroutine to print an error message for an input read-error. C SUBROUTINE READ_ERROR TYPE 160 160 FORMAT(' Read error reading input file') RETURN END C Subroutine to output the prime numbers to a data file. C SUBROUTINE OUTPUT_TO_DATAFILE(IPRIMES_TABLE, ICOUNT) DIMENSION IPRIMES_TABLE(ICOUNT) OPEN(UNIT=2, FILE='PRIMESOUT.DAT', STATUS='NEW') WRITE (2, 200) (IPRIMES_TABLE(I), I=1,ICOUNT) 200 FORMAT(I5) CLOSE(UNIT=2) RETURN END