0

I am working on the project euler lattice path problem in Javascript. I used the recursive method and solved it in project euler. Below is my function,

const latticePathsRecursive = (m, n = m) => {
    if (m < 0 || n < 0) return 0;
    if (m === 0 && n === 0) return 1;
    return (latticePathsRecursive(m - 1, n) + latticePathsRecursive(m, n - 1));
}

I tried the same in Hackerrank(test cases have both square & rectangular grid) but all the hidden test cases timed out and failed.

So I tried using Combinatorial Solution and except for the sample test case and one hidden test case all the other test cases failed - wrong answer.

I can't figure out where it went wrong. But why 3 test cases pass and the rest throws wrong answer? Am I missing something while using the formula here?

const latticePathsCombinatorial = (a, b) => {
   const factorial = (number) => {
      if (number === 1 || number === 0) {
         return 1;
      } else {
         return number * factorial(number - 1);
      }
   }

   let n = a + b,
   k = a;

   // 'n choose k' = n! / (k! * (n - k)!)
   return factorial(n) / (factorial(k) * factorial(n - k));
}

Thanks in advance.

SangyK
  • 799
  • 2
  • 6
  • 16
  • I am fairly certain that your code is failing because there is a constraint you have not noticed on Hackerrank: "As number of ways can be very large, print it modulo (10^9 + 7)." – kelsny Jan 04 '23 at 15:26
  • @vera. Actually, while printing I added modulo (10^9+7). `console.log(latticePathsCombinatorial(n, m) % 1000000007)`. – SangyK Jan 04 '23 at 16:47
  • Yeah but the number is too big to be accurately represented. It's already incorrect before you use modulo. – kelsny Jan 04 '23 at 16:48
  • Maybe BigInt will work I guess. Let me try it out. Thanks. – SangyK Jan 04 '23 at 16:49

1 Answers1

0

The issue is solved, when I converted all the numbers to BigInt. Since some answers are too big, handling everything in BigInt solved the problem.

let M = 1000000007n;
        
let n = BigInt(a) + BigInt(b),
    k = BigInt(a);
let res = (factorial(n) / (factorial(k) * factorial(n - k))) % M;
return Number(res);
SangyK
  • 799
  • 2
  • 6
  • 16