From 596af479c74ac3fda984cf17c0cdc69fa43579c7 Mon Sep 17 00:00:00 2001 From: Matthew Naylor Date: Tue, 15 Apr 2025 09:45:25 +0100 Subject: [PATCH] Improvement to prime-sieve model solution It is simpler and cheaper to eliminate multiples of `p` using a stride rather than checking every number for divisibility by `p`. --- solutions/section2.03-2/solution.f90 | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/solutions/section2.03-2/solution.f90 b/solutions/section2.03-2/solution.f90 index eb2f612..a27ce8d 100644 --- a/solutions/section2.03-2/solution.f90 +++ b/solutions/section2.03-2/solution.f90 @@ -23,30 +23,26 @@ program exercise2 implicit none integer, parameter :: nmax = 120 - integer, dimension(2:nmax) :: ia logical, dimension(2:nmax) :: isprime integer :: n, p do n = 2, nmax - ia(n) = n isprime(n) = .true. end do do p = 2, nmax - do n = 2*p, nmax - if (mod(n,p) == 0) isprime(n) = .false. + do n = 2*p, nmax, p + isprime(n) = .false. end do ! One could use an array construct... - !where (mod(ia(2*p:), p) == 0) - ! isprime(2*p:) = .false. - !end where + !isprime(2*p::p) = .false. end do ! Results do n = 2, nmax - print *, "n is prime: ", ia(n), isprime(n) + print *, "n is prime: ", n, isprime(n) end do print *, "Number of primes: ", count(isprime)