import math
from decimal import Decimal

BIG_BUT_NOT_INFINITE = 1e30
F = 100
H = 80

def solve(F, H, pr_h=.5, eps=1e-6):
  # X(f, h) := expected number of flips to win given we need h heads out of f
  #            flips and optimal strategy
  # X(f, h) := { 0             if h = 0
  #            { X(F, H)       if f < h
  #            { min(          otherwise
  #                1 + X(f-1, h-1) * Pr(h) + X(f-1, h) * (1 - Pr(h)),
  #                X(F, H)
  #              )
  #
  # X(f, h) depends on X(F, H) so it can't be computed.
  # So introduce X_est(F, H) as a guess for X(F, H).
  # And introduce X_conv(f, h) which is X(f, h) but it uses X_est(F, H)
  # instead of X(F, H) in the definition above.
  #
  # If X_est(F, H) <= X(F, H), then X_conv(F, H) = X_est(F, H).
  # This is because it will just "restart" and return X_est(F, H) immediately.
  # So we can find the largest value of X_est(F, H) for which X_conv(F, H) != X_est(F, H).
  # That should be the correct value of X_est(F, H).

  pr_h_d = Decimal(pr_h)
  eps_d = Decimal(eps)

  def x_conv(x_est):
    cache = {}
    def x(f, h):
      if h == 0: return 0
      if f < h: return x_est
      
      cache_key = (f, h)
      if cache_key not in cache:
        do_flip = 1 + x(f-1, h-1) * pr_h_d + x(f-1, h) * (1 - pr_h_d)
        cache[cache_key] = min(do_flip, x_est)
      return cache[cache_key]
    return x
  
  lo = Decimal(H)
  hi = Decimal(BIG_BUT_NOT_INFINITE)
  while hi - lo > eps_d:
    x_est_guess = (lo + hi) / Decimal(2)
    x_conv_guess = x_conv(x_est_guess)(F, H)
    if abs(x_conv_guess - x_est_guess) < eps_d:
      lo = x_est_guess
    else:
      hi = x_est_guess
  
  return x_conv(lo)

oracle = solve(F, H)

# How many flips at the start of the game?
print(oracle(F, H))
print(oracle(2, 2))
print(oracle(20, 20))
print(oracle(40, 40))
