Commit 86850300 authored by Nayuki's avatar Nayuki

P52: Added Haskell solution, tweaked Java and Python solutions.

parent b5cc9663
{-
- Solution to Project Euler problem 52
- Copyright (c) Project Nayuki. All rights reserved.
-
- https://www.nayuki.io/page/project-euler-solutions
- https://github.com/nayuki/Project-Euler-solutions
-}
import Data.List (sort)
main = putStrLn (show ans)
ans = head (filter cond [1 .. ])
cond x = all (multeq x) [2 .. 6]
multeq x i = (sort (show x)) == (sort (show (i * x)))
......@@ -17,23 +17,28 @@ public final class p052 implements EulerSolution {
public String run() {
outer:
for (int i = 1; ; i++) {
for (int j = 2; j < 6; j++) {
if (!hasSameDigits(i * j, i * (j + 1)))
continue outer;
}
return Integer.toString(i);
if (i > Integer.MAX_VALUE / 6)
throw new ArithmeticException("Overflow");
if (multiplesHaveSameDigits(i))
return Integer.toString(i);
}
}
private static boolean hasSameDigits(int x, int y) {
char[] xdigits = Integer.toString(x).toCharArray();
char[] ydigits = Integer.toString(y).toCharArray();
Arrays.sort(xdigits);
Arrays.sort(ydigits);
return Arrays.equals(xdigits, ydigits);
private static boolean multiplesHaveSameDigits(int x) {
for (int i = 2; i <= 6; i++) {
if (!Arrays.equals(toSortedDigits(x), toSortedDigits(i * x)))
return false;
}
return true;
}
private static char[] toSortedDigits(int x) {
char[] result = Integer.toString(x).toCharArray();
Arrays.sort(result);
return result;
}
}
......@@ -10,10 +10,9 @@ import itertools
def compute():
for i in itertools.count(1):
digits = sorted(str(i))
if all(sorted(str(i * j)) == digits for j in range(2, 7)):
return str(i)
cond = lambda i: all(sorted(str(i)) == sorted(str(j * i)) for j in range(2, 7))
ans = next(i for i in itertools.count(1) if cond(i))
return str(ans)
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