I am just doing my first steps with Fortran, and the initial joy of having 128-bit integers has vanished...
program multiples_of_3_and_5
implicit none
! n is the number to test whether it is divisible by 3 or 5
!
! kind = 8 defines a 64-bit integer (8 bytes = 64 bits)
integer(kind=8) :: n
! n stores the sum of all n which are divisible by either 3 or 5
integer(kind=8) :: s
do n = 1, 1000-1
print *, "n = ", n
if (mod(n, 3) == 0 .or. mod(n, 5) == 0) then
print *, "n is divisible by either 3 or 5"
s = s + n
end if
print *, "s = ", s
end do
print *,"The result is: ", s
end program multiples_of_3_and_5
When I use kind=4
or 16
or 32
, it doesn't give the correct result anymore - even when no integer overflow occurs.
Edit: Example output (with kind=16
)
n is divisible by either 3 or 5
s = -23552265132012064450548819805997922555
n = 996
n is divisible by either 3 or 5
s = -23552265132012064450548819805997921559
n = 997
s = -23552265132012064450548819805997921559
n = 998
s = -23552265132012064450548819805997921559
n = 999
n is divisible by either 3 or 5
s = -23552265132012064450548819805997920560
The result is: -23552265132012064450548819805997920560