To add n numbers on p processors, each processor first adds its own share, then the partial sums are combined in pairs, round after round, until one sum is left.
What to build
A program that counts the cycles of this parallel sum and compares it with a single processor.
Requirements
- The numbers are shared out as evenly as possible, so the largest share has ceil(n ÷ p) numbers. One addition takes one cycle, so the local phase takes
ceil(n ÷ p) − 1cycles. - Only min(n, p) processors have numbers. In each combining round the active processors work in pairs (one may be left alone), so the count becomes ceil(count ÷ 2). A round costs 1 cycle for the addition plus c cycles to send a partial sum.
- Print
local L,rounds Randtotal Twith T = L + R × (1 + c). Then printserial Swith S = n − 1 andspeedup Xwith X = S ÷ T to 2 decimals.
Input
One line: n, p, c.
Output
Five lines.
Constraints
2 ≤ n ≤ 10⁶; 1 ≤ p ≤ 1000; 0 ≤ c ≤ 100.
Example
Input:
1000 8 1
Output:
local 124
rounds 3
total 130
serial 999
speedup 7.68
Why it works
The local phase is perfectly parallel, but combining the results is not: each round halves the number of active processors, so the number of rounds grows like log₂ of the processor count and the communication cost keeps the speedup below p.
Examples
1000 8 1
local 124 rounds 3 total 130 serial 999 speedup 7.68
16 1 5
local 15 rounds 0 total 15 serial 15 speedup 1.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The processor with the biggest share has ceil(n / p) numbers and needs that many minus one additions. Only min(n, p) processors have numbers.
Hint 2
Combine the partial sums in rounds: each round halves the number of processors, rounding up, and costs 1 + c cycles. Count rounds with a loop: while count > 1, count = (count + 1) // 2.
Hint 3
Speedup = serial cycles (n - 1) ÷ total cycles.
Solution
Show one correct solution (try it yourself first)
n, p, c = map(int, input().split())
local = (n + p - 1) // p - 1
count = min(n, p)
rounds = 0
while count > 1:
count = (count + 1) // 2
rounds += 1
total = local + rounds * (1 + c)
s = n - 1
print("local", local)
print("rounds", rounds)
print("total", total)
print("serial", s)
print(f"speedup {s / total:.2f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step