Problem:
Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes

Solution in Ruby (2.3.3) (judge verdict: Runtime Error)

class Position
  def initialize(x, y, count = 0)
    @x, @y = x, y
    @count = count
  end
  attr_accessor :x, :y, :count

  def up
    Position.new(x, y - 1, @count + 1)
  end

  def down
    Position.new(x, y + 1, @count + 1)
  end

  def left
    Position.new(x - 1, y, @count + 1)
  end

  def right
    Position.new(x + 1, y, @count + 1)
  end
end

class Matrix
  def initialize(map)
    @map    = map
  end

  def get(pos)
    @map[pos.y][pos.x]
  end
  
  def set(pos, newVal)
    @map[pos.y][pos.x] = newVal
  end

  def print
    @map.each do |row|
      puts row.inspect
    end
  end

  def blank_count
    cnt = 0
    @map.each do |row|
      row.each do |e|
        cnt += 1 if e == Maze::BLANK || e == Maze::GOAL
      end
    end
    return cnt
  end
end

class Maze
  GOAL = 'G'
  BLANK = '.'
  WALL  = '#'
  attr_accessor :maze

  def initialize(maze, visited)
    @maze    = maze
    @visited = visited
  end

  def is_goal?(pos)
    @maze.get(pos) == GOAL
  end

  def available?(pos)
    @maze.get(pos) == BLANK && !@visited.get(pos)
  end
  
  def steps_to_goal
    q = [Position.new(1, 1)]
    while (s = q.shift)
      @visited.set(s, true)
      [s.up, s.down, s.left, s.right].each do |nxt|
        return nxt.count if is_goal?(nxt)
        if available?(nxt)
          q << nxt
        end
      end
    end
  end

  def blank_count
    @maze.blank_count
  end

  def turnable_cell_count
    blank_count - (steps_to_goal + 1)
  end
end

H, W = STDIN.gets.split(' ').map(&:to_i)
maze = []
maze << Array.new(H + 2, '#')
H.times do
  maze << ['#'] + STDIN.gets.chomp.split('') + ['#']
end
maze << Array.new(H + 2, '#')
maze[H][W] = Maze::GOAL

map     = Matrix.new(maze)
visited = []
(H+2).times do
  visited << Array.new(W + 2, false)
end
visited = Matrix.new(visited)

puts Maze.new(map, visited).turnable_cell_count