INF = 1 << 29
COINS = [500,100,50,10,5,1]
while gets
  l = $_.split.map(&:to_i)
  p = l.shift
  break if p == 0
  ret = INF
  for change in 0..499
    ps = cs = 0
    pay = p + change
    for k in 0..5
      m = [pay/(c=COINS[k]), l[5-k]].min
      ps += m
      pay -= m*c
      m = change / c
      cs += m
      change -= m*c
    end
    ret = ps + cs if ret > (ps + cs)
  end
  p ret
end