Solution to Project Euler Problem 15: Lattice paths - Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid?
Updated: May 29, 2023 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Project Euler Problem 15: Lattice paths.
Difficulty: Easy.
Objective: Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
Input: None.
Expected Output: 137846528820.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
import java.math.BigInteger;
public class SikademyEulerSolution {
public String run() {
return Library.binomial(40, 20).toString();
}
// Returns n!.
public static BigInteger factorial(int n) {
if (n < 0)
throw new IllegalArgumentException("Factorial of negative number");
BigInteger prod = BigInteger.ONE;
for (int i = 2; i <= n; i++)
prod = prod.multiply(BigInteger.valueOf(i));
return prod;
}
// Returns n choose k.
public static BigInteger binomial(int n, int k) {
if (k < 0 || k > n)
throw new IllegalArgumentException();
BigInteger product = BigInteger.ONE;
for (int i = 0; i < k; i++)
product = product.multiply(BigInteger.valueOf(n - i));
return product.divide(factorial(k));
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
import math
def binomial(n, k):
assert 0 <= k <= n
return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
def compute():
return str(binomial(40, 20))
if __name__ == "__main__":
print(compute())