Project Euler #15: Lattice paths

  • + 0 comments
    import java.util.Scanner;
    
    public class Solution {
        public static long factorial(int n) {
            long result = 1;
            for (int i = 1; i <= n; i++) {
                result = (result * i) % (1000000007);
            }
            return result;
        }
    
        public static long pow(long base, long exponent, long mod) {
            long result = 1;
            base = base % mod;
            while (exponent > 0) {
                if (exponent % 2 == 1) {
                    result = (result * base) % mod;
                }
                exponent = exponent / 2;
                base = (base * base) % mod;
            }
            return result;
        }
    
        public static long modInverse(long a, long m) {
            return pow(a, m - 2, m);
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int t = scanner.nextInt();
            scanner.nextLine(); // Consume newline left-over
            for (int i = 0; i < t; i++) {
                String[] item = scanner.nextLine().split(" ");
                int n = Integer.parseInt(item[0]);
                int m = Integer.parseInt(item[1]);
                long answer = (factorial(n + m) * modInverse((factorial(n) * factorial(m)) % 1000000007, 1000000007)) % 1000000007;
                System.out.println(answer);
            }
        }
    }