Generic Custom Operator Functions: A Curious Case of a Bad * Instruction

前端 未结 1 569
臣服心动
臣服心动 2021-01-25 06:15

I run into this problem, while playing with generics and custom operators in Swift. In the code snippet below, I am introducing two new prefix operators, ∑ and ∏ and then implem

相关标签:
1条回答
  • 2021-01-25 06:47

    That is a simple integer overflow. You try to compute the factorial

    1 * 2 * ... * 100 = 100!
    = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
    ≈ 9.33 × 10^157
    

    according to Wolfram Alpha. With an initial value of 0 instead of 1, all products are zero and the overflow does not occur.

    ∏(1...20) = 2432902008176640000
    

    works as expected and is the largest factorial that can be stored in a 64-bit integer.

    In Swift, integer calculations do not "wrap around", but cause an exception if the result does not fit into the target datatype.

    Swift has special "overflow operators" &+, &*, ... with a different overflow behavior for integer calculations, see "Overflow Operators" in the Swift documentation.

    0 讨论(0)
提交回复
热议问题