Commit e5dae135 by Nayuki

### P26, P91: Revamped short algorithms for clarity.

parent e4906a7e
 ... ... @@ -34,13 +34,14 @@ public final class p026 implements EulerSolution { private static int getCycleLength(int n) { Map stateToIter = new HashMap<>(); int state = 1; int iter = 0; while (!stateToIter.containsKey(state)) { stateToIter.put(state, iter); state = state * 10 % n; iter++; for (int iter = 0; ; iter++) { if (stateToIter.containsKey(state)) return iter - stateToIter.get(state); else { stateToIter.put(state, iter); state = state * 10 % n; } } return iter - stateToIter.get(state); } }
 ... ... @@ -22,7 +22,8 @@ public final class p091 implements EulerSolution { for (int y1 = 0; y1 <= LIMIT; y1++) { for (int x2 = 0; x2 <= LIMIT; x2++) { for (int y2 = 0; y2 <= LIMIT; y2++) { if (y2 * x1 < y1 * x2 && isRightTriangle(x1, y1, x2, y2)) // For uniqueness, ensure that (x1,y1) has a larger angle than (x2,y2) // For uniqueness, ensure that (x1,y1) has a larger angle than (x2,y2) if (y2 * x1 < y1 * x2 && isRightTriangle(x1, y1, x2, y2)) count++; } } ... ... @@ -32,13 +33,14 @@ public final class p091 implements EulerSolution { } // Tests whether {(0,0), (x1,y1), (x2,y2)} forms a right triangle. // Tests whether the three points {(0,0), (x1,y1), (x2,y2)} form a right triangle. private static boolean isRightTriangle(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; return x1*x1 + y1*y1 + x2*x2 + y2*y2 == dx*dx + dy*dy || x1*x1 + y1*y1 + dx*dx + dy*dy == x2*x2 + y2*y2 || x2*x2 + y2*y2 + dx*dx + dy*dy == x1*x1 + y1*y1; int a = x1 * x1 + y1 * y1; int b = x2 * x2 + y2 * y2; int c = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); return a + b == c || b + c == a || c + a == b; } }
 ... ... @@ -6,6 +6,8 @@ # https://github.com/nayuki/Project-Euler-solutions # import itertools def compute(): ans = max(range(1, 1000), key=reciprocal_cycle_len) ... ... @@ -15,12 +17,12 @@ def compute(): def reciprocal_cycle_len(n): seen = {} x = 1 i = 0 while x not in seen: seen[x] = i x = x * 10 % n i += 1 return i - seen[x] for i in itertools.count(): if x in seen: return i - seen[x] else: seen[x] = i x = x * 10 % n if __name__ == "__main__": ... ...
 ... ... @@ -19,14 +19,12 @@ def compute(): return str(ans) # Tests whether {(0,0), (x1,y1), (x2,y2)} forms a right triangle. # Tests whether the three points {(0,0), (x1,y1), (x2,y2)} form a right triangle. def is_right_triangle(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 a = x1 * x1 + y1 * y1 b = x2 * x2 + y2 * y2 c = dx * dx + dy * dy return a + b == c or b + c == a or c + a == b a = x1**2 + y1**2 b = x2**2 + y2**2 c = (x2 - x1)**2 + (y2 - y1)**2 return (a + b == c) or (b + c == a) or (c + a == b) if __name__ == "__main__": ... ...
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment