0

I was solving Project Euler problems using Fortran; the problem is to create a Fibonacci sequence and find the sum of all even numbers that come under 4 million. Here's what I wrote

implicit none
integer*4::a(1:4000000),sum
integer*4::i,maxc
maxc = 3999999

a(1) = 1
a(2) = 2
do i = 3,maxc,1
   a(i) = a(i-1) + a(i-2)
end do
sum = 0
do i = 1,maxc
   if (mod(a(i),2)==0) then
      sum = sum + a(i)
   end if
end do
print*,sum


end

The output is -1833689714 Any idea what went wrong?

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
  • Also, please note that using `integer*4` is not well defined across compilers. See [here](https://stackoverflow.com/questions/3170239/fortran-integer4-vs-integer4-vs-integerkind-4) for details. – Alexander Vogt Feb 18 '18 at 15:24

1 Answers1

0

Due to the size of the integer kind you chose, there is a limit to the numbers you can represent. In your code it is 2147483647 (with gfortran, obtained by print *,huge(sum)). It can be shown that this limit is exceeded for i=59 in your implementation. Then, you get an integer overflow, and the value becomes negative.

Simply using a floating point representation for the sum, i.e.

real :: sum

Does the trick.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
  • Wouldn't double precision be better? – albert Feb 18 '18 at 15:50
  • @albert: In this case, the outcome is small enough to fit into the range of a single precision float. One could argue that the precision could make a difference... I tried, but the results are the same. – Alexander Vogt Feb 18 '18 at 15:54