← All lessonsUnit 1 · Swift for problems
Lesson 1.7

Whole-number arithmetic

/ counts how many whole times one number goes into another, % counts what is left over, and an Int has only so much room.

Reach for it when
You divide, round up, take digits apart, or count something that grows very large.
The move
/ drops the remainder and % is the remainder. (a + b - 1) / b divides rounding up. An Int that overflows stops the program.
Cost
Each is one step.

The idea

Harper

I walked home from the market with two eggs in my coat pocket.

Arthur

On purpose?

Harper

Swift told me to. We'll come back to the coat. Twenty eggs on a table, and boxes that hold six. How many boxes can you fill?

Arthur

Three. That's eighteen eggs.

Harper

And the other two?

Arthur

Left over. Two eggs don't fill a box.

Harper

Say it in Swift.

Arthur

20 / 6 is 3, the full boxes. 20 % 6 is 2, the eggs left over. One operator for each question.

Harper

My calculator says seven divided by two is three and a half.

Arthur

In Swift 7 / 2 is 3. Your calculator isn't using Ints, and an Int has no half of a box. Three full boxes of two, and one egg that / keeps quiet about. % is the one that owns up to it.

Harper

And when everything fits?

Arthur

Then % says 0. Nothing left on the table.

Harper

Now I have to get all twenty home. How many boxes do I need?

Arthur

Four. The last two eggs need a box as well, even though they won't fill it.

Harper

And 20 / 6 told me?

Arthur

Three. You asked it how many boxes you could fill. You wanted how many you'd need.

Harper

That explains the coat.

Arthur

How is the coat?

Harper

It has had better days. So have the eggs.

That is the whole tool: / counts the full boxes, and % counts what is left over. Everything else in this lesson is those two with the right question put to them, and one warning: an Int is a box too, and it has only so much room.

The shape

This is what you know by heart:

Swift
/// How `eggs` go into boxes that hold `size` eggs each.
func boxes(_ eggs: Int, _ size: Int) -> [Int] {
    let full = eggs / size                    // the boxes you can fill
    let leftOver = eggs % size                // the eggs left on the table
    let needed = (eggs + size - 1) / size     // the boxes it takes to hold every egg
    return [full, leftOver, needed]
}

It has three lines, and each answers a different question.

For 20 eggs and boxes of 6 the three lines give [3, 2, 4]: 3 boxes filled, 2 eggs left over, 4 boxes needed.

Everywhere in this lesson the numbers are zero or more, and the number you divide by is at least 1. "What goes wrong" says what happens outside that.

Watch it run

The boxes hold 6. Here are the three lines for 16 eggs up to 20, and the sum that the third line divides.

eggsboxes filledleft overeggs + 5boxes needed
1624213
1725223
1830233
1931244
2032254

Look at the rows for 18 and 19. 18 eggs leave nothing over. 18 + 5 is 23, one egg short of a fourth box, so the boxes needed are the boxes filled. 19 eggs leave 1 over. 19 + 5 is 24, and there is the fourth box.

Look down the third column too. What is left over climbs to 5 and starts again from 0. It never reaches 6.

Step by step

Step 1

The quotient and the remainder of two numbers

How many whole times one number goes into another is called the quotient. What is left over is called the remainder. They are the first two lines of the shape under their proper names.

Swift
/// How many whole times `divisor` goes into `number`, then what is left over.
func quotientAndRemainder(_ number: Int, _ divisor: Int) -> [Int] {
    let quotient = number / divisor      // the full boxes
    let remainder = number % divisor     // what is left over
    return [quotient, remainder]
}

What is new: between two Ints, / gives the quotient and % gives the remainder. For 20 and 6 this gives [3, 2].

Nothing goes missing between the two. The quotient times the divisor, plus the remainder, is the number again: 3 × 6 + 2 is 20.

7 / 2 is 3, not 3.5. An Int has nowhere to keep a half. And when the number is smaller than the divisor, no box is filled at all: 4 and 9 give [0, 4].

Step 2

Is a number even? Is it a multiple of k?

Both questions ask one thing: is anything left over?

Swift
/// Whether `number` is even.
func isEven(_ number: Int) -> Bool {
    number % 2 == 0                  // boxes of two, and nothing left over
}

What is new: a remainder of 0 means that everything fitted. An even number goes into boxes of two with nothing left over. 10 does. 7 does not: it leaves 1.

Put any k where the 2 is, and the question becomes whether the number is a multiple of k: whether it is k taken some whole number of times.

Swift
/// Whether `number` is a multiple of `k`.
func isMultiple(_ number: Int, of k: Int) -> Bool {
    number % k == 0                  // boxes of k, and nothing left over
}

For 12 and 6 it answers true, and for 20 and 6 it answers false. Zero is even, and it is a multiple of every k: no eggs fill no boxes and leave nothing over.

Swift has this built in as number.isMultiple(of: k), and you may use it. Learn the line with % all the same. The next step needs the remainder itself, not a yes or no about it.

Step 3

The last digit of a number, and the number without it

Now the boxes hold ten.

Swift
/// The last digit of `number`, then the number without it.
func lastDigitAndRest(_ number: Int) -> [Int] {
    let last = number % 10           // what is left over from boxes of ten
    let rest = number / 10           // the full boxes of ten
    return [last, rest]
}

What is new: with boxes of ten, the eggs left over are the number's last digit, and the boxes filled are the number with that digit taken off. 472 eggs fill 47 boxes of ten and leave 2, so the answer is [2, 47].

That is what the digits of a number say. The 2 at the end of 472 is what is left over from the tens, and the 47 in front of it counts the tens.

A number below ten fills no box. All of it is left over, and the number without its last digit is 0: 7 gives [7, 0].

Step 4

Every digit of a number, last one first

Take the last digit, drop it, and do the same to the rest. This step takes it in two moves.

Swift
/// Every digit of `number`, the last one first.
func digitsLastFirst(_ number: Int) -> [Int] {
    var rest = number
    var digits: [Int] = []
    repeat {
        digits.append(rest % 10)     // take the last digit
        rest = rest / 10             // and drop it
    } while rest > 0                 // go again while rest still has digits
    return digits
}

First, the loop. What is new: doing step 3 again and again until there are no digits left to take. On each pass % 10 takes the last digit, / 10 drops it, and rest carries the other digits into the next pass. Here it is for 472.

passrest beforerest % 10rest / 10digits after
1472247[2]
24774[2, 7]
3440[2, 7, 4]

Look at the last row. 4 / 10 is 0, because 4 eggs fill no box of ten, and that 0 is what ends the loop.

The digits come out last one first, [2, 7, 4], because the last digit is the only one % can reach. When a problem wants the first digit first, reverse the array at the end.

Then the number 0. What is new: repeat, a loop that makes one pass before it asks whether to go on. Every number has at least one digit, even 0: digitsLastFirst(0) is [0]. A plain while rest > 0 loop would ask first, find nothing to do, and hand back [], as if 0 had no digits at all.

Step 5

Divide rounding up (7 bananas at 3 an hour take 3 hours)

This is the third line of the shape with hours for boxes. An hour holds 3 bananas, and an hour that is begun counts as a whole one.

Swift
/// The hours it takes to eat `bananas` at `perHour` an hour.
/// An hour that is begun counts as a whole one.
func hoursToEat(_ bananas: Int, _ perHour: Int) -> Int {
    (bananas + perHour - 1) / perHour
}

What is new: adding one less than perHour before you divide. 7 bananas at 3 an hour take 3 hours: two full hours, and a third for the last banana. Plain 7 / 3 says 2, and leaves a banana on the table.

Why one less than perHour, and not perHour itself? Try 6 bananas, which take exactly 2 hours. (6 + 3 - 1) / 3 is 2. (6 + 3) / 3 is 3: add a whole hour's worth and you always get a whole hour more, even when nothing was left over.

With any two names it is the same line: (a + b - 1) / b. The sum in it has to fit in an Int as well, and with the numbers that problems give, it does. A later lesson, "Searching on the answer", is built on this line.

Dividing two Doubles and rounding up looks like another way. It is not: a Double loses count of large numbers, and "What goes wrong" shows one. This step's second problem gives you a different slip to mend, a version that adds 1 after it divides.

Step 6

Keep a growing count small with % 1_000_000_007 after every addition

Some counts grow past what an Int has room for, and an Int that is asked to hold too much stops the program. Step 7 looks at that. A problem with such a count asks for less: what is left over when the count is put into boxes of 1,000,000,007. Problems call that the count modulo 1,000,000,007, and the code calls the number modulus. In Swift it can be written 1_000_000_007, so that the zeros can be counted.

Here is a count that grows fast. It starts at 1, and each pass adds the count to itself.

Swift
/// 1 doubled `times` times over, keeping only the remainder by 1,000,000,007.
func doubled(_ times: Int) -> Int {
    let modulus = 1_000_000_007
    var count = 1
    for _ in 0..<times {
        count = (count + count) % modulus     // a full box goes, what is left stays
    }
    return count
}

What is new: taking the remainder after every addition, and not once at the end. A full box can be sent away the moment it is full: taking away exactly 1,000,000,007 leaves what is left over as it was. So the count stays below 1,000,000,007 from one pass to the next, and nothing about the answer changes.

Ten doublings give 1,024: a number smaller than the box is left alone by %. The thirtieth doubling is the first to fill a box. The plain count would be 1,073,741,824, and doubled(30) is 73,741,817: the same count with one full box sent away. A hundred doublings make a count of 31 digits, which no Int could hold, and doubled(100) is 976,371,285 all the same.

Why this number? Problems have settled on it, and it is small. Two remainders added together come to 2,000,000,012 at the most, which an Int holds with room to spare.

Step 7

Find where a running product overflows Int

An Int is a box too. This step takes it in three moves.

First, what a full Int does. What is new: an Int has a largest number, Int.max, which is 9,223,372,036,854,775,807. Ask it to hold more, by adding or by multiplying, and Swift does not quietly lose the extra. The program stops. That is an overflow.

Plain * gives no warning: by the time you could look at the product, the program has stopped. So Int has a second way to multiply, which reports and carries on.

Next, one multiplication.

Swift
/// Whether `number` times `factor` is too big for an `Int`.
func overflows(_ number: Int, times factor: Int) -> Bool {
    let report = number.multipliedReportingOverflow(by: factor)
    return report.overflow
}

What is new: multipliedReportingOverflow(by:). It multiplies and hands back two things together. One of them is overflow, which is true when the product did not fit. A billion times a billion is a 1 with 18 zeros, and overflow is false. Ten billion times a billion is a 1 with 19 zeros, and overflow is true.

Then many multiplications. Multiply the numbers of an array together one at a time, keeping the product so far. That is a running product. What is new is only partialValue, the other thing that comes back: the product, when it fitted.

Swift
/// Multiplies the numbers together one at a time. The position of the first number that
/// makes the product too big for an `Int`, or `nil` when the whole product fits.
func firstOverflow(_ numbers: [Int]) -> Int? {
    var product = 1
    for i in numbers.indices {
        let report = product.multipliedReportingOverflow(by: numbers[i])
        if report.overflow {
            return i                         // this number did not fit
        }
        product = report.partialValue        // it fitted: keep the product
    }
    return nil
}

For the numbers 1 to 25 the answer is 20, the position that holds the number 21. The product of 1 to 20 is 2,432,902,008,176,640,000, which fits, and 21 times that does not. When overflow is true, partialValue is not the product: for Int.max times 2 it is -2. So the function returns before it reads it.

For seventy 2s the answer is 62, the position of the 63rd: 62 doublings fit and the 63rd does not. That is where doubled in step 6 would have stopped the program without its %.

What goes wrong

Expecting a half. 7 / 2 is 3, and 1 / 2 is 0. Between two Ints the part after the point is dropped, not rounded.

Dividing by zero. When divisor is 0, number / divisor stops the program, and so does number % divisor: there are no boxes of size zero. The problems here promise a divisor of at least 1. When a problem does not, test for zero before you divide.

A number below zero. -7 / 2 is -3 and -7 % 2 is -1. The part after the point is dropped here too, so -3.5 becomes -3 and not -4, and the remainder takes the sign of the number being divided. So number % 2 == 1 misses every odd number below zero: ask number % 2 != 0. The problems here keep to zero and above.

Rounding up by always adding one. eggs / size + 1 is right until the eggs fill their boxes exactly. For 18 eggs and boxes of 6 it says 4, and one box goes home empty. (eggs + size - 1) / size says 3.

Rounding up through Double. ceil needs an import, which this course never has. Int((Double(eggs) / Double(size)).rounded(.up)) needs none, but a Double holds every whole number only up to 9,007,199,254,740,992. For one egg more than that and boxes of 2 it answers 4,503,599,627,370,496. The whole-number line answers 4,503,599,627,370,497. One egg is back in a coat pocket.

Asking before the first digit. For 0, a while rest > 0 loop hands back []: no digits at all. repeat makes one pass and then asks.

The remainder only at the end. count % 1_000_000_007 after the loop is too late. On doubling number 63 the plain count overflows, and the program stops before it reaches the %.

Looking for an overflow after it has happened. if product * number > Int.max can never be true. No Int is larger than Int.max, and the program stops at the * before anything is compared.

Say it back

1

What do 20 / 6 and 20 % 6 give, and what does each count?

Show the answerHide the answer

3 and 2. / counts the boxes you can fill, and % counts the eggs left over.

2

How do you ask whether a number is a multiple of k?

Show the answerHide the answer

number % k == 0: nothing is left over. With 2 for k, it asks whether the number is even.

3

Which two lines take a number's last digit and then drop it?

Show the answerHide the answer

number % 10 is the last digit, and number / 10 is the number without it.

4

Why does the digit loop make one pass before it asks whether to go on?

Show the answerHide the answer

Every number has at least one digit. A loop that asked first would hand back no digits for 0.

5

A problem wants a count's remainder by 1,000,000,007. When do you take it, and why then?

Show the answerHide the answer

After every addition. A full box can go the moment it is full without changing what is left over, and the count never grows large enough to overflow.

6

What happens when a product is too big for an Int, and how do you find out without it happening?

Show the answerHide the answer

The program stops. multipliedReportingOverflow(by:) multiplies and reports: overflow is true when the product did not fit, and partialValue is the product when it did.

7

Why did two eggs go home in Harper's coat pocket?

Show the answerHide the answer

She counted her boxes with 20 / 6, which is 3: the boxes she could fill. The 2 eggs left over had no box. The boxes she needed were (20 + 6 - 1) / 6, which is 4.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1The quotient and the remainderEasy
2Is it even?Easy
3Is it a multiple of k?Easy
4The last digit, and the number without itEasy
5Every digit, last one firstEasy
6Zero has a digit tooEasy
7Hours to eat the bananasEasy
8One box too manyEasy
9A count that stays smallEasy
10Is the product too big for an Int?Easy
11Where a running product overflowsEasy

These problems are done in the Orithms Mac app.

Every piece of code and every number in a lesson comes from a file that was compiled and run.