我试图总结低于200万的所有素数。我已经查看了几个小时的代码,但是我找不到导致它打印出错误号码的原因。
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
它应该是1179908152
142913828922
答案 0 :(得分:4)
总和溢出32位整数。使total
成为64位整数,并确保初始化它:
integer, parameter :: int64 = selected_int_kind(16) ! dec. digits
integer (kind = int64) :: total
total = 0
您的程序还认为2不是素数,因为对于n == 2
,upto
是2,可以被2整除。从{{+ 1
中删除upto
项是安全的。 1}},当你用32位浮点算术计算平方根时,至少你的整数不超过16,777,216。
最后,你可以通过在求和时不考虑偶数来加速你的程序(当然,以2的总和开始)。您在isprime
中的循环也可以处理偶数作为特例并仅迭代奇数。