Question Error: Arithmetic operation resulted in an overflow

Alex Garbiak

New member
Joined
May 3, 2011
Messages
3
Programming Experience
Beginner
Background

I am trying to create a Fibonacci number sequence with the number of terms decided by the user through a ASP drop down box. The Fibonacci sequence is then displayed in a ASP label control further down the page.

The code (below) works fine for up to 45 or so terms. However if a user selects a value above this, say 50, then the following error is thrown:

OverflowException was unhandled by user code. Arithmetic operation resulted in an overflow.

The error is thrown on the line ArrayFibNums(i) = ArrayFibNums(i - 1) + ArrayFibNums(i - 2) in the code shown below:

Code

VB.NET:
Protected Function FibonaccciNumbers() As Array
        Dim NumInSequence As Integer = 0
        NumInSequence = CInt(DdlstNumInSequence.SelectedItem.Value)
        Dim ArrayFibNums(NumInSequence - 1) As Integer

        ArrayFibNums(0) = 1
        ArrayFibNums(1) = 1
        For i As Integer = 2 To NumInSequence - 1
            ArrayFibNums(i) = ArrayFibNums(i - 1) + ArrayFibNums(i - 2)
        Next
        Return ArrayFibNums
End Function

Why is this error thrown? What am I doing wrong and what is the solution to this problem? I'm a beginner "programmer" so I have no idea, just seems a bit random to me.

P.S. I realise this is not a very efficient or elegant way to generate the Fibonacci sequence. I may try to do it through recursion if I can be bothered. I am purely doing this for self-interest purposes (related to the Euler Problem 2 if anyone is interested).
 
2,147,483,647 is the max value that an integer can be in VB.NET. You are getting above that value. The below code produces the same exception, possibly try using a Long instead which can hold a heck of a lot bigger numbers:

VB.NET:
        Dim i As Integer = 0
        Try
            Do Until 1 = 0
                i += 1
            Loop
        Catch ex As ArithmeticException
            MsgBox(ex.Message)
        End Try
 
64-bit numbers I believe are the maximum, if you need go above 9,223,372,036,854,775,807 (9 pentillion) there may be a way to create your own data type but I think C++ is more suited for something of that nature. Possibly there is someone more knowledgeable than I in this area.
 
Back
Top