### constant

MAX_INT = 1 << 30

COINS = [1, 5, 10, 50, 100, 500]
RCOINS = COINS.reverse

### subroutines

def changes(pn)
  count = 0

  for cn in RCOINS
    k = pn / cn
    count += k
    pn -= k * cn
  end

  count
end

### main

loop do
  pn, *nis = gets.strip.split(' ').map(&:to_i)
  break if pn == 0

  min_num = MAX_INT
  num = 0

  5.downto(0) do |i|
    ci = COINS[i]
    k = [pn / ci, nis[i]].min
    num += k
    pn -= ci * k

    if pn == 0
      min_num = num if min_num > num
      #p [i, pn, min_num, num]
      break
    end

    if nis[i] > k
      num0 = num + 1 + changes(ci - pn)
      min_num = num0 if min_num > num0
    end
    #p [i, pn, min_num, num]
  end

  puts min_num
end