# QuestionError: Arithmetic operation resulted in an overflow

#### Alex Garbiak

##### New member
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).

#### ss7thirty

##### Well-known member
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``````

#### Alex Garbiak

##### New member
Ok thanks. That makes sense. So if I changed the code from using Integer variables to Double then this would solve my problem?

#### ss7thirty

##### Well-known member
Oops just edited my post:

ss7thirty said:
try using a Long instead which can hold a heck of a lot bigger numbers

#### Alex Garbiak

##### New member
Oops just edited my post:

Sorry didn't see that before. That works perfectly thanks for your help.

Out of curiosity though, what would I do if I wanted to generate the Fibonacci numbers to well beyond the maximum value a Long / Double could store?

#### ss7thirty

##### Well-known member
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.

Replies
1
Views
1K
Replies
1
Views
192
Replies
1
Views
249
Replies
8
Views
804
Replies
1
Views
369