Simple Swift Fibonacci program crashing (Project Euler 2)

前端 未结 2 471
梦谈多话
梦谈多话 2020-12-07 04:32

I am trying to solve the second problem on Project Euler. The problem is as follows:


Each new term in the Fibonacci sequence is generated by adding the pre

2条回答
  •  悲&欢浪女
    2020-12-07 05:19

    There is nothing weird about this at all. Do you know how large the 400 fibonacci number is?

    176023680645013966468226945392411250770384383304492191886725992896575345044216019675
    

    Swift Int64 or UInt64 simply cannot handle that large of a number. The later can go up to 18446744073709551615 at max - not even close.

    If you change your variables to be doubles it works but will be inaccurate:

    var prev : Double = 0
    var next : Double = 1
    var num : Double = 0
    var sum : Double = 0
    

    will yield

    2.84812298108489e+83

    which is kind of close to the actual value of

    1.76e+83

    Luckily you do not need to get values that big. I would recommend not writing a for loop but a while loop that calculates the next fibonacci number until the break condition is met whose values do not exceed four million.

提交回复
热议问题