Problem overview
A shop gives one free cup for every 6 cups bought. The constant cups holds the number of cups paid for, and the program must print the total number of cups received: the paid ones plus the free ones.
With 12 paid cups there are two complete groups of 6, so 2 cups are free, and the total is 14. With the starter value, 213 paid cups, the answer is 248.
Approach
The only hard part is counting the free cups. One free cup is earned per complete group of 6 paid cups. A partial group earns nothing, so 5 paid cups give no free cup, and 13 paid cups give two, not 2.17.
That is exactly what integer division does. When both operands are Int, Swift's / drops the fractional part. So cups / 6 is the number of complete groups, and therefore the number of free cups. The total is cups + cups / 6.
Step by step
- Divide
cupsby 6. For 213 this is 35, because 6 fits into 213 thirty-five times (6 * 35 = 210) with 3 left over, and the leftover is discarded. - Add the paid cups. 213 + 35 is 248. Division runs before addition, so no parentheses are needed.
- Print the sum.
The solution in Swift
let cups: Int = 213
print(cups + cups / 6)
The output is:
248
Swift details:
- Integer division truncates toward zero. For positive counts like these, that is the same as rounding down. The behaviour differs only for negative numbers, which don't occur with a cup count.
IntstaysInt. The result ofcups / 6is anInt, so it adds tocupsdirectly. Swift refuses to add anIntand aDoublewithout an explicit conversion.- Division by zero stops the program. Here the divisor is the literal 6, so it never happens.
The leftover cups
The remainder is the part of the division that the quotient throws away. cups % 6 is 3 for 213 cups, which means 3 paid cups sit in an unfinished group, and 3 more purchases would earn the next free cup. The exercise needs only the quotient, but the quotient and the remainder always go together: 213 is 6 * 35 + 3.
Edge cases and common mistakes
- Fewer than 6 paid cups. With 5,
5 / 6is 0, so the total is 5. - Exactly 6. The first group is complete: 6 + 1 = 7, matching the task's description.
- Free cups don't earn more free cups. Only paid cups count toward a group, which is why the division uses
cupsand not the running total. - Rounding up. With 13 paid cups, a rounded-up count would give 3 free cups. Integer division gives 2.
- Using
Doublearithmetic.Double(cups) / 6is 2.1666 for 13 cups, which is not a number of cups.
Testing
cups = 12prints14.cups = 213prints248.cups = 5prints5.cups = 6prints7.cups = 0prints0.
Key takeaways
- Dividing two
Intvalues gives the number of complete groups. - "One for every N" is a quotient:
count / N. - The total is the paid amount plus the quotient.
