From 5b86e3b1327d3e502411935c7cc1b4667c6b1372 Mon Sep 17 00:00:00 2001 From: Correl Roush Date: Sat, 24 Sep 2011 20:48:50 -0400 Subject: [PATCH] Exercise 004 --- e004.erl | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 e004.erl diff --git a/e004.erl b/e004.erl new file mode 100644 index 0000000..2db10f1 --- /dev/null +++ b/e004.erl @@ -0,0 +1,30 @@ +% Find the largest palindrome made from the product of two 3-digit numbers. + +% A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. +% Find the largest palindrome made from the product of two 3-digit numbers. + +-module(e004). +-export([ + main/1 +]). + +product(Min, Max) -> + product(Min, Max, Max, Max, 0). +product(Min, _, N1, _, Product) when N1 < Min -> + Product; +product(Min, Max, N1, N2, Product) when N2 < Min -> + product(Min, Max, N1 - 1, Max, Product); +product(Min, Max, N1, N2, Product) -> + P = trunc(N1 * N2), + S = integer_to_list(trunc(N1 * N2)), + R = lists:reverse(S), + if + S == R, P > Product -> + product(Min, Max, N1, N2 - 1, P); + true -> + product(Min, Max, N1, N2 - 1, Product) + end. + +main(_) -> + io:format("Largest palindrome product of 2-digit numbers: ~w~n", [product(10, 99)]), + io:format("Largest palindrome product of 3-digit numbers: ~w~n", [product(100, 999)]).