Problem:
Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.

Solution in Ruby (2.3.3) (judge verdict: Accepted)

# ABC 145 D - Knight
# https://atcoder.jp/contests/abc145/tasks/abc145_d

x, y = gets.chomp.split(/ /).map(&:to_i)

class Factorial
  def self.calc(n)
    new(n).get(n)
  end

  def initialize(max, mod)
    @max = max
    @mod = mod

    @array = []
    set_up
  end

  attr_reader :max, :mod, :array

  def get(n)
    raise ArgumentError if n > max
    @array[n]
  end

  private

  def set_up
    array.push(1) # 0
    array.push(1) # 1

    if max >= 2
      2.upto(max) do |i|
        f = array.last * i
        f = f % mod unless mod.nil?
        array.push(f)
      end
    end
  end
end

class Inverse
  def initialize(max, mod)
    @max = max
    @mod = mod

    @array = []
    set_up
  end

  attr_reader :max, :mod, :array

  def get(n)
    array[n]
  end

  private

  def set_up
    array.push(nil) # 0
    array.push(1)   # 1

    if max >= 2
      2.upto(max) do |i|
        inv = mod - array[mod % i] * (mod / i) % mod
        array.push(inv)
      end
    end
  end
end

class FactorialInverse
  def initialize(max, inverse, mod)
    @max = max
    @inverse = inverse
    @mod = mod

    @array = []
    set_up
  end

  attr_reader :max, :inverse, :mod, :array

  def get(n)
    array[n]
  end

  private

  def set_up
    array.push(1) # 0
    array.push(1) # 1

    if max >= 2
      2.upto(max) do |i|
        finv = array.last * inverse.get(i) % mod
        array.push(finv)
      end
    end
  end
end

class Combination
  def self.calc(n, k, mod)
    if n < k
      0
    elsif n < 0 || k < 0
      0
    else
      factorial = Factorial.new(n, mod)
      inverse = Inverse.new(n, mod)
      factorial_inverse = FactorialInverse.new(n, inverse, mod)
      factorial.get(n) * (factorial_inverse.get(k) * factorial_inverse.get(n - k) % mod) % mod
    end
  end
end

if (x + y) % 3 == 0
  mod = 10 ** 9 + 7
  n = (x + y) / 3
  k = x - n

  puts Combination.calc(n, k, mod)
else
  puts 0
end