**Problem:**

NOTE: This problem is a significantly more challenging version of Problem 81.

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red and is equal to 2297.

131 673 234 103 18

201 96 342630 803 746 422 111

537 699 497 121 956

805 732 524 37 331

Find the minimal path sum, in matrix.txt (right click and 'Save Link/Target As...'), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by moving left, right, up, and down.

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red and is equal to 2297.

131 673 234 103 18

201 96 342630 803 746 422 111

537 699 497 121 956

805 732 524 37 331

Find the minimal path sum, in matrix.txt (right click and 'Save Link/Target As...'), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by moving left, right, up, and down.

**Solution:**

100

**Code:**

The solution may include methods that will be found here: Library.java .

The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}

/*

* Solution to Project Euler problem 33

* By Nayuki Minase

*

* http://nayuki.eigenstate.org/page/project-euler-solutions

* https://github.com/nayuki/Project-Euler-solutions

*/

public final class p033 implements EulerSolution {

public static void main(String[] args) {

System.out.println(new p033().run());

}

/*

* Consider an arbitrary fraction n/d:

* Let n = 10 * n1 + n0 be the numerator.

* Let d = 10 * d1 + d0 be the denominator.

* As stated in the problem, we need 10 <= n < d < 100.

* We must disregard trivial simplifications where n0 = d0 = 0.

*

* Now, a simplification with n0 = d0 is impossible because:

* n1 / d1 = n / d = (10*n1 + n0) / (10*d1 + n0).

* n1 * (10*d1 + n0) = d1 * (10*n1 + n0).

* 10*n1*d1 + n1*n0 = 10*d1*n1 + d1*n0.

* n1*n0 = d1*n0.

* n1 = d1.

* This implies n = d, which contradicts the fact that n < d.

* Similarly, we cannot have a simplification with n1 = d1 for the same reason.

*

* Therefore we only need to consider the cases where n0 = d1 or n1 = d0.

* In the first case, check that n1/d0 = n/d; in the second case, check that n0/d1 = n/d.

*/

public String run() {

int numer = 1;

int denom = 1;

for (int d = 10; d < 100; d++) {

for (int n = 10; n < d; n++) {

int n0 = n % 10, n1 = n / 10;

int d0 = d % 10, d1 = d / 10;

if (n1 == d0 && n0 * d == n * d1 || n0 == d1 && n1 * d == n * d0) {

numer *= n;

denom *= d;

}

}

}

return Integer.toString(denom / Library.gcd(numer, denom));

}

}

## No comments :

## Post a Comment