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
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.