In slow start the window doubles every round trip, starting from 1 segment.
What to build
A program that says how many round trips slow start needs to reach a window of W segments, and how many segments were sent on the way.
Requirements
- Round 1 has a window of 1 segment, round 2 has 2, round 3 has 4, and so on.
- Print
rounds R: the first round whose window is at least W. - Print
segments S: the total number of segments sent in rounds 1 to R.
Input
One whole number W.
Output
Two lines: rounds R and segments S.
Constraints
1 ≤ W ≤ 1000000.
Example
Input:
10
Output:
rounds 5
segments 31
Why it works
Doubling means the window after r rounds is 2 to the power r − 1, so it takes about log2 of W rounds to reach W, which is very fast. The sum of 1, 2, 4, ... is always one less than the next power of two.
Examples
10
rounds 5 segments 31
1
rounds 1 segments 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Round 1 sends 1 segment, round 2 sends 2, round 3 sends 4: round r sends 2 ** (r - 1).
Hint 2
Stop at the first round whose window is at least W.
Hint 3
The total sent is the sum of the windows of all rounds up to and including that one.
Solution
Show one correct solution (try it yourself first)
w = int(input())
window, rounds, total = 1, 1, 1
while window < w:
window *= 2
rounds += 1
total += window
print("rounds", rounds)
print("segments", total)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step