Program to find expected growth of virus after time t in Python

Suppose there is a dangerous virus that grows rapidly. The probability of virus cells growing by a factor x is 0.5, and the probability of growing by a factor y is also 0.5. Starting with a single virus cell, we need to calculate the expected number of virus cells after time t. If the result is large, we return it modulo 10^9+7.

The expected growth factor at each time step is (x + y) / 2, since each factor has probability 0.5.

Problem Analysis

At each time step, the virus can grow by factor x or y with equal probability. The expected growth factor is:

Expected factor = 0.5 × x + 0.5 × y = (x + y) / 2

After t time steps, the expected number of cells is ((x + y) / 2)^t.

Example Walkthrough

For x = 2, y = 4, t = 1:

  • Expected growth factor = (2 + 4) / 2 = 3
  • After t = 1: 3^1 = 3 cells
  • Verification: 0.5 × (1 × 2) + 0.5 × (1 × 4) = 1 + 2 = 3

Algorithm Steps

  • Calculate factor = (x + y) // 2 (integer division)
  • Use fast exponentiation to compute factor^t mod (10^9+7)
  • Fast exponentiation reduces time complexity from O(t) to O(log t)

Implementation

def solve(x, y, t):
    m = 10**9 + 7
    factor = (x + y) // 2
    res = 1
    
    # Fast exponentiation: compute factor^t mod m
    while t > 0:
        if t % 2 == 1:  # If t is odd
            res = (res * factor) % m
        factor = (factor * factor) % m
        t = t // 2
    
    return res

# Test case
x = 2
y = 4
t = 1
result = solve(x, y, t)
print(f"Expected virus cells after {t} time: {result}")
Expected virus cells after 1 time: 3

Testing with Larger Values

def solve(x, y, t):
    m = 10**9 + 7
    factor = (x + y) // 2
    res = 1
    
    while t > 0:
        if t % 2 == 1:
            res = (res * factor) % m
        factor = (factor * factor) % m
        t = t // 2
    
    return res

# Test with larger time values
test_cases = [
    (2, 4, 1),
    (2, 4, 2), 
    (3, 5, 3),
    (2, 6, 10)
]

for x, y, t in test_cases:
    result = solve(x, y, t)
    expected_factor = (x + y) // 2
    print(f"x={x}, y={y}, t={t} ? factor={expected_factor}, result={result}")
x=2, y=4, t=1 ? factor=3, result=3
x=2, y=4, t=2 ? factor=3, result=9
x=3, y=5, t=3 ? factor=4, result=64
x=2, y=6, t=10 ? factor=4, result=48576

How Fast Exponentiation Works

Fast exponentiation computes a^n in O(log n) time by repeatedly squaring:

  • If n is even: a^n = (a^2)^(n/2)
  • If n is odd: a^n = a × a^(n-1)

Conclusion

This solution uses fast exponentiation to efficiently compute the expected virus growth after time t. The expected growth factor is (x + y) / 2, and we calculate factor^t mod (10^9+7) in O(log t) time complexity.

Updated on: 2026-03-26T18:25:51+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements