When downloading a large file in chunks, you must determine how many chunks (or parts) are necessary. The partSize
is the size of each chunk, and fileSize
is the total size of the file.
The Basic Idea
If a file is exactly divisible by the part size, you can simply divide fileSize
by partSize
to get the number of parts. For example:
- Example 1: If
fileSize
is 10 MB andpartSize
is 5 MB, the file can be divided into 2 parts (10 MB / 5 MB = 2 parts).
However, if the file size isn’t exactly divisible by the part size, you’ll have a leftover portion that still needs to be downloaded as a smaller final part.
- Example 2: If
fileSize
is 12 MB andpartSize
is 5 MB, dividing 12 MB by 5 MB gives you 2.4, which means you need 2 full parts and a small extra part. You can’t have a fraction of a part, so you need to round up to 3 parts.
The Challenge: Rounding Up
In programming, dividing two integers like fileSize / partSize
usually discards the remainder and rounds down to the nearest whole number. This is called integer division.
- Example 3:
12 MB / 5 MB
= 2 (but actually, you need 3 parts).
To account for the leftover part and effectively “round up” to the next whole number when there’s a remainder, you can use the formula:
Breaking Down the Formula: (fileSize + partSize - 1) / partSize
- Add
partSize - 1
:- By adding
partSize - 1
, you’re ensuring that any remainder after dividingfileSize
bypartSize
will cause the division to round up instead of down. - Example 4: If
fileSize = 12 MB
andpartSize = 5 MB
:partSize - 1
is5 MB - 1 byte
= 4,999,999 bytes.- Adding this to
fileSize
:12 MB + 4,999,999 bytes
= 16,999,999 bytes.
- By adding
- Divide by
partSize
:- Now, when you divide by
partSize
, the result is effectively rounded up: - Example 5:
16,999,999 bytes / 5 MB
= approximately 3 parts.
- Now, when you divide by
Why Does This Work?
- Scenario 1: No Remainder (file size is a multiple of part size):
- If
fileSize = 10 MB
andpartSize = 5 MB
:fileSize + partSize - 1 = 10 MB + 5 MB - 1 byte = 14,999,999 bytes
.14,999,999 bytes / 5 MB = 2 parts
.- This gives the correct result because no rounding is needed.
- If
- Scenario 2: Remainder Exists (file size isn’t a multiple of part size):
- If
fileSize = 12 MB
andpartSize = 5 MB
:fileSize + partSize - 1 = 12 MB + 5 MB - 1 byte = 16,999,999 bytes
.16,999,999 bytes / 5 MB = 3 parts
.- The rounding up happens automatically, ensuring you account for the leftover portion.
- If
Summary
The formula (fileSize + partSize - 1) / partSize
ensures that the number of parts is correctly calculated, even when the file size isn’t an exact multiple of the part size. By adding partSize - 1
before dividing, you force the division to round up, ensuring that any remaining bytes are included in an additional part.