Search code examples
swift4

EXC_BAD_INSTRUCTION code=EXC_I386_INVOP on Fibonacci count function


I'm very newbie with Swift (and non-dynamic typed languages), and trying to make a function which makes an array of the first 100 Fibonacci numbers.

Here is it:

func buildFibonacci(){
    var numbers: [Int64] = [0,1]
    for x in (2...99) {    
        numbers.append(numbers[x-1] + numbers[x-2])
    }
    print(numbers)
}

buildFibonacci()

But when I run it, on 93-th iteration I get an error:

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

As far as I understand, it is being raised on the sum operation.

My guess that this is something about size of Int so I changed it into Int64, but it looks like the problem was in something else. I use swift 4.1, if it is important. Could someone please help me?


Solution

  • Your assumption is right, it's an overflow exception, the number becomes too high to be represented in 64 bit. On 64 bit machines Int is Int64 anyway so the type change makes no difference.

    A solution is to use NSDecimalNumber which is not restricted to 64 bit and provides basic arithmetic methods.

    func buildFibonacci(){
        var numbers: [NSDecimalNumber] = [.zero, .one]
        for x in 2...99 {
            numbers.append(numbers[x-1].adding(numbers[x-2]))
        }
        print(numbers)
    }
    
    buildFibonacci()