I need to generate some big integers. See example below.
Input Result
40 165580141
80 37889062373143906
120 8670007398507948658051921
160 1983924214061919432247806074196061
200 453973694165307953197296969697410619233826
Here is my Fortran code:
program cycle
use iso_fortran_env
implicit none
character(200) :: str
integer :: n
integer(kind=int64) :: x1, result, x2, x3
do n = 40, 500, 40
x1 = n
result = 1
x2 = 0
x3 = 1
do
if (x1 > 1) then
x2 = result
result = result + x3
x3 = x2
x1 = x1 - 1
else
exit
end if
end do
write(str,'(i64)') result
print *, n, adjustl(str)
end do
end program cycle
Here is the sample output:
40 165580141
80 37889062373143906
120 790376311979428689
160 9217463444206948445
200 3721511182311577122
As you can see, it gets the first two numbers right but the rest are beyond the reach of 64 bit integers. I've looked at other questions (1) but I'm really interested in a simple way, preferably built into the language itself. In Ruby and Go I have little trouble. Am I overlooking something obvious in Fortran? Is there a better option I can use in my code?
There is no built-in "big number" support, but we can first check whether there is a larger integer kind available (as mentioned by francescalus above and also many previous pages (e.g. this page). On my computer with gfortran-6.1, the compiler seems to support 128-bit integer kind, so I could calculate the result up to n=160 or so.
Results:
While there is no built-in "BigInt" type, it is rather straight-forward to use an external library (for example, fmlib linked from this page). Since various operators and assignment are overloaded, almost no modifications are necessary to your codes.
Procedures:
1) Download FM.95, FMZM90.f95, and FMSAVE.f95 (the file names should be changed by dropping ".txt").
2) Make a library file as
3) Modify your code as follows (the modified parts are marked with arrows).
4) Compile (assuming that "test.f90" is the above code):
5) Results
We can verify the result by noting that
result
forn
is actually equal to fibonacci(n+1), so for example we have fibonacci(481) forn = 480
.