Fortran: possible fibonacci logical error -


i wrote program in fortran display fibonacci numbers x term:

program fibonacci implicit none integer :: x,p,c,i,t !initializes limit, previous, current, iterative, , temp print *, "list first x fibonacci numbers: " read *, x      !reads limit p=0            !sets previous 0 c=1            !sets current 1 i=1,x     print *, c !prints current fibonacci number t = c      !sets temporary variable current c = c + p  !sets current current plus previous p = t      !sets previous temporary value end         !iterates until reaches limit 'x' end program fibonacci 

when compile , run it, , enter number 10, expected list first x fibonacci numbers:

10        1        1        2        3        5        8       13       21       34       55 

but when entered 50: list first x fibonacci numbers:

50        1        1        2        3        5        8       13       21       34       55       89      144      233      377      610      987     1597     2584     4181     6765    10946    17711    28657    46368    75025   121393   196418   317811   514229   832040  1346269  2178309  3524578  5702887  9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 -1323752223 512559680 -811192543 -298632863 

i don't know problem is, far can see, logic sound have suggestions? i'm using gfortran compiler, way

i'm no fortran expert, did take class once...

apparently you're using 4 byte integer (http://www-classes.usc.edu/engr/ce/108/text/fbk01.htm) these. after, 1836311903 you're exceeding maximum integer value (2147483647) , calculations overflowing.

you have 2 options calculating fibonacci numbers more precision. first, can find system/fortran compiler combination support 8 or 16 byte integers. support in gfortran @ least, seems system specific. option use multiple precision library gmp.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -