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


Suppose there is a dangerous virus and that grows rapidly. The probability of number of virus cells growing by a factor x is 0.5 and also the probability of number of virus cells growing by a factor y is 0.5. Now if there was a single cell of virus at beginning, then calculate the expected number of virus cells after t time. If the answer is too large, then mod result by 10^9+7.

So, if the input is like x = 2, y = 4, t = 1, then the output will be 3, because initially, the virus has only one cell. After x time, with probability 0.5, its size is doubled (x2) and, with probability of the other 0.5, its size grows by 4 times. Thus, the expected number of virus cell after time t = 1 is: 0.5*2*1 + 0.5*4*1 = 3.

To solve this, we will follow these steps −

  • m = 10^9+7
  • factor := floor of (x+y)/2
  • res:= 1
  • while t > 0, do
    • if t is odd, then
      • res :=(res*factor) mod m
    • factor :=(factor*factor) mod m
    • t := floor of t/2
  • return res

Example

Let us see the following implementation to get better understanding −

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

   return res

x = 2
y = 4
t = 1
print(solve(x, y, t))

Input

2, 4, 1

Output

3

Updated on: 25-Oct-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements