This repository was archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler4.ex
More file actions
50 lines (37 loc) · 1.25 KB
/
euler4.ex
File metadata and controls
50 lines (37 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule Euler4 do
import String
def solve do
IO.puts inspect :timer.tc(Euler4, :find_largest_palindrome, [3])
end
def find_largest_palindrome(num_digits) do
start_num = round(:math.pow(10, num_digits - 1))
end_num = binary_to_integer(String.duplicate("9", num_digits))
find_largest_palindrome(start_num, start_num, end_num, 0)
end
defp find_largest_palindrome(x, y, max_num, answer) when x < max_num and y < max_num do
new_answer = x * y
cond do
is_palindrome?(new_answer) and new_answer > answer ->
find_largest_palindrome( x, y + 1, max_num, new_answer)
true ->
find_largest_palindrome( x, y + 1 , max_num, answer)
end
end
defp find_largest_palindrome(x, y, max_num, answer) when x < max_num do
new_answer = x * y
cond do
is_palindrome?(new_answer) and new_answer > answer ->
find_largest_palindrome( x + 1, x + 1, max_num, new_answer)
true ->
find_largest_palindrome( x + 1, x + 1, max_num, answer)
end
end
defp find_largest_palindrome(_, _, _, answer) do
answer
end
defp is_palindrome?(x) when is_integer(x) do
string_x = to_string(x)
reverse_string_x = reverse(string_x)
string_x === reverse_string_x
end
end