We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def power(a, b):
res = 1
a %= MOD
while b > 0:
if b % 2 == 1:
res = (res * a) % MOD
a = (a * a) % MOD
b //= 2
return res
def modInverse(n):
return power(n, MOD - 2)
def precompute_factorials():
for i in range(2, MAX_R):
FACT[i] = (FACT[i-1] * i) % MOD
def combinations(n, k):
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
if k > n // 2:
k = n - k
numerator = FACT[n]
denominator = (FACT[k] * FACT[n - k]) % MOD
return (numerator * modInverse(denominator)) % MOD
def solve_matrix_tracing(M, N):
R = M + N - 2
K = M - 1
if R < 0:
return 0
return combinations(R, K)
if name == 'main':
precompute_factorials()
try:
t_line = sys.stdin.readline()
if not t_line:
sys.exit(0)
t = int(t_line.strip())
for _ in range(t):
try:
line = sys.stdin.readline().rstrip().split()
if not line:
continue
M = int(line[0])
N = int(line[1])
result = solve_matrix_tracing(M, N)
print(result)
except EOFError:
break
except Exception as e:
continue
except Exception as e:
pass
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Tracing
You are viewing a single comment's thread. Return to all comments →
import sys
MAX_R = 2000001 MOD = 10**9 + 7 FACT = [1] * MAX_R
def power(a, b): res = 1 a %= MOD while b > 0: if b % 2 == 1: res = (res * a) % MOD a = (a * a) % MOD b //= 2 return res
def modInverse(n): return power(n, MOD - 2)
def precompute_factorials(): for i in range(2, MAX_R): FACT[i] = (FACT[i-1] * i) % MOD
def combinations(n, k): if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 if k > n // 2: k = n - k
def solve_matrix_tracing(M, N): R = M + N - 2 K = M - 1
if name == 'main': precompute_factorials()