Reputation: 319
I am attempting to sum up all the prime numbers below 2 million. I've gone over my code for hours but I cannot find what is causing it to print out the faulty number.
logical function isprime(n) result(response)
implicit none
integer :: i
integer, intent(in) :: n
integer :: upto
if (n <= 1) then
response = .false.
return
end if
upto = int(n**.5)
do i = 3, upto, 2
if (mod(n, i) == 0) then
response = .false.
return
end if
end do
response = .true.
end function isprime
program problem10
implicit none
integer :: n
logical :: isprime
integer, parameter :: int64 = selected_int_kind(16)
integer(kind = int64) :: total
do n = 1, 2000000
if (isprime(n)) then
total = total + n
end if
end do
print *, total
end program problem10
It's printing 1179908152
when it should be 142913828922
Upvotes: 1
Views: 796
Reputation: 29126
The sum overflows 32-bit-integers. Make total
a 64-bit integer and also make sure to initialise it:
integer, parameter :: int64 = selected_int_kind(16) ! dec. digits
integer (kind = int64) :: total
total = 0
Your program also thinks 2 isn't prime, because for n == 2
, upto
is 2, which is divisible by 2. It is safe to delete the + 1
term from upto
, at least as long your integers don't exceed 16,777,216 when you calculate the square root with 32-bit float arithmetics.
Finally, you can speed up your program by not considering even numbers when summing (and start with a sum of 2, of course). Your loop in isprime
could also handle even numbers as special case and iterate over odd numbers only.
Upvotes: 4