Chat app~15 min2s · 256 MBtarget O(sqrt n) time, O(1) spacenumber-theory
A chat app stores an archive of messages and shows it in pages. Every page has the same number of messages, and the last page must be full. So a page size works only when it divides the number of messages exactly.
Your team lead wants to know how many different page sizes are possible for an archive of a given size. A size of 1 and a size equal to the whole archive both count.
Write page_sizes(messages).
messages that divides messages with no remainder.Input: messages = 36
Output: 9The divisors of 36 are 1, 2, 3, 4, 6, 9, 12, 18, 36. They come in pairs whose product is 36. The pair 6 and 6 is the same number, so it counts once.
| Smaller divisor | Partner (36 divided by it) | Sizes added |
|---|---|---|
| 1 | 36 | 2 |
| 2 | 18 | 2 |
| 3 | 12 | 2 |
| 4 | 9 | 2 |
| 6 | 6 | 1 |
The answer is 9.
Input: messages = 13
Output: 213 is a prime. Its only divisors are 1 and 13, so the answer is 2.
Input: messages = 1
Output: 1With 1 message there is one page size, 1.
1 ≤ messages ≤ 10^12Trying every size from 1 to n takes up to 10^12 steps. A judge allows about 10^8 steps in 2 seconds, so that is far too slow.
The square root of 10^12 is 10^6. Trying the sizes up to the square root takes about 10^6 steps, which is fast. The number itself needs 64 bits, because 10^12 is more than 2^31.