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 Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)

import java.io.*;
import java.math.*;
import java.util.*;
public class Main { 

	public static void main(String[] args) { //BRUH
		Scanner input = new Scanner(System.in);
		long X = input.nextLong();
		long Y = input.nextLong();
		long ans = 0;
		long mod = (long)(1e9+7);
		long[] fact = new long[1000001]; //[Factorial,Inverse]
		fact[1]=1;
		for (long i = 2; i <= 1000000; i++) {
			fact[(int) i]=fact[(int) (i-1)]*i;
			fact[(int) i]%=mod;
		}
		if ((X+Y)%3==0) {
			long min = Math.min(X, Y);
			long max = Math.max(X, Y);
			if (max<=min*2) {
				if (max==min*2) ans=1;
				else {
					long diff = max-min;
					long sub = min-diff;
					long totalMoves = sub/3; //Each move increases sum of coordinates by 3
					totalMoves*=2; //Each move alters x AND y though so need to 
					//multiply by 2 to avoid WA
					max-=sub;
					min-=sub;
					totalMoves+=min;
					long chooseOptions = sub/3;//(3,3) requires one of each knight move
					long inv1 = FastExp(fact[(int) chooseOptions],mod-2,mod);
					long inv2 = FastExp(fact[(int) (totalMoves-chooseOptions)],mod-2,mod);
					ans=fact[(int) totalMoves];
					ans*=inv1;
					ans%=mod;
					ans*=inv2;
					ans%=mod;
				}
			}
		}
		System.out.println(ans);
	}	
	public static long FastExp(long base, long exp, long mod) {
		long ans = 1;
		while (exp>0) {
			if (exp%2==1) ans*=base;
			base*=base;
			exp/=2;
			base%=mod;
			ans%=mod;
		}
		return ans;
	}
}