# Integer overflow

Hi all ,
I have written program below which occurs integer overflow in factorial operation for n > 31

How can i handle this?

2 Likes

A quick google search says that the maximum 32bit integer value is `2,147,483,647`.
So you can’t calculate any values larger than this without increasing the size of the integer you’re using.
I expect that your program is not giving correct answers for factorials above `12!`

One option for a larger integer, is to use the `int64` kind from the `iso_fortran_env` module:

``````program main
use iso_fortran_env, only: int64
implicit none
integer(int64) :: n, i, s_1, s_2, s_3, factorial
...
end program main
``````

According to google, max value for 64bit int is `9,223,372,036,854,775,807`.
If you don’t need the precision, you could also just use a float-point (`real`) variable for your factorial result.

1 Like

Thank you very much 1 Like

The intrinsic `huge` returns the maximum value in a given variable type.

``````print *, huge(factorial)
``````

prints the maximum value that can be stored in a default integer variable as `factorial`.

3 Likes

@ELNS,
if you come from Python, you can be disappointed because in Python you can use arbitrarily long integers:

``````>>> 44568668*345346344747*57457455585*353523463473474585*66347474735583
20743094674690460723155872026108386637422588202843490781776300L
``````

But in Fortran, you will need a specific library to do such things (there is surely one, but don’t ask me…)
Fortran uses the hardware to compute fast. Python can go beyond but at the expense of the speed.

3 Likes