Search code examples
swiftunsigned-integer

UIint64 data overflow issue


I was solving a problem:

Each new term in the Fibonacci sequence is generated by adding
the previous two terms. By starting with 1 and 2, the first 10
terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values
do not exceed four million, find the sum of the even-valued terms.

and below is my solution:

class FB {
  static func run() {
    var a: UInt64 = 0
    var b: UInt64 = 1

    var c: UInt64 = 0

    var sum: UInt64 = 0

    for _ in 0..<4_000_000 {
      print(c)
      c = a + b // CRASHES
      if c % 2 == 0 {
        sum += c
      }

      a = b
      b = c
    }

    print("SUM: , \(sum)")
  }
}

But it crashes as mentioned in comment Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

What data type should I use in order to avoid overflow for c variable?


Solution

  • .. whose values do not exceed four million

    means that c must not be greater than 4 million.

    Replace

    for _ in 0..<4000000 {
    

    with

    while c < 4000000 {
    

    Now the numeric type can even be UInt32 😉