program prime c implicit none c character*9 filename logical lflag integer nmax , icount , n real cputot , etime c real tdummy ( 2) c external divisor , etime c cputot = etime ( tdummy ) c filename = "prime.txt" open (10, file=filename, status="unknown") c c write( 6,2010) read ( 5, *) nmax write( 6,2011) nmax, filename write(10,2020) nmax c c Loop over all integers .le. nmax, and report all the prime c numbers. c icount = 0 do 10 n=2,nmax call divisor ( n, lflag ) if (lflag .eqv. .true.) then icount = icount + 1 write(10,2030) n endif 10 continue write( 6,2040) icount, nmax write(10,2040) icount, nmax c close ( 10 ) c cputot = etime ( tdummy ) - cputot write( 6,2050) cputot c c----------------------------------------------------------------------- c----------------------- Write format statements ----------------------- c----------------------------------------------------------------------- c 2010 format("PRIME : Enter the maximum integer to be checked for " 1 ,"prime.") 2011 format("PRIME : All prime numbers less than or equal to ",i4 1 ," are listed in file ",/ 2 ,'PRIME : ''',a9,'''.') 2020 format('PRIME : The following is a list of all prime numbers ' 1 ,'.le. ',i8,'.',/) 2030 format('PRIME : ',i9) 2040 format('PRIME :',/ 1 ,'PRIME : There are ',i8,' prime numbers less than or ' 2 ,'equal to ',i8,'.') 2050 format('PRIME :',/ 1 ,'PRIME : Total cpu usage for this run is ',1pg12.5 2 ,' seconds.') c stop end c c subroutine divisor ( number, lflag ) c c----------------------------------------------------------------------- c implicit none c logical lflag integer number , imax ,i , num real rnum , sqrtnum , small , qty c data small / 0.0001 / c c----------------------------------------------------------------------- c lflag = .true. if (number .le. 3) return c c The maximum divisor that needs to be checked is the greatest c integer less than or equal to the square root of the number (‘imax’). c The lowest divisor is 2. Thus, check all divisors between 2 and c ‘imax’. As soon as one divisor is found, set ‘lflag’ to .false., c (i.e., "number" is not prime) and return to the calling program. c rnum = real ( number ) sqrtnum = sqrt ( rnum ) imax = int ( sqrtnum + small ) do 10 i=2,imax qty = rnum / real ( i ) num = i * int ( qty + small ) if ( num .eq. number ) then lflag = .false. return endif 10 continue c return end c