Dealing with large numbers in Swift

Type inference is a handy feature in Swift that makes declaring most variables fun and easy. However, there are cases when you must explicitly define the type of the variable.

In this example, the starting point is having 4 big numbers, each consisting of 50 digits. Normally you might try to put them into a variable with type inference, like this:

var numbers =
    [37107287533902102798797998220837590246510135740250,
    46376937677490009712648124896970078050417018260538,
    74324986199524741059474233309513058123726617309629,
    91942213363574161572522430563301811072406154908250]

Since the compiler is getting an integer like number fed to it, it tries to automatically use the type Int (Int64 on a 64-bit platform, Int32 on a 32-bit platform). This leads to a compile-time error of an overflow. Since the numbers are too big even for an UInt64 type, we must use floating point here. With floating point there is less precision, but let’s not worry too much about that right now.

var numbers : Double[] =
[37107287533902102798797998220837590246510135740250,
    46376937677490009712648124896970078050417018260538,
    74324986199524741059474233309513058123726617309629,
    91942213363574161572522430563301811072406154908250]

Now the code compiles!

If you want to calculate the sum of these, you can simply do the following:

var sum : Double = 0
for number in numbers
{
    sum += number
}
sum

As you see here I must again explicitly define the “sum” variable to be of type Double due to the size of the numbers being calculated. However, I can use type inference in the for-in loop for the constant called “number” since the numbers array is already of type Double[].

 
41
Kudos
 
41
Kudos

Now read this

Looping through an array of arrays with Swift

…and finding the greatest product horizontally, vertically or diagonally. Finding out the largest product was fairly simple using Swift. The global enumerate function for looping through the arrays was an especially nice feature. It... Continue →