Problem 4 is an interesting one. “A palindromic number reads the same both ways. Find the largest palindrome made from the product of two 3-digit numbers.”
I thought about this for a few minutes and decided the best way to approach it would be to build candidate palindromic numbers and and then test them to see if they were the product of two 3 digit numbers.
It’s easy to see that the product of two 3 digit numbers could at most be 6 digits, so I decided that I would start building my candidate palindromes by counting down from 999 and adding the mirror of the number as a suffix. Example – take 998 and add 899 to the end for 998899. Then I would test each candidate by dividing by all possible three digit numbers and seeing if I could find a three digit cofactor for any even divisions. For example, if a candidate was evenly divisible by 123, was the cofactor also a three digit number?
So this problem was mostly centered in the approach. Once I’d settled on that, the Erlang code came easily. A little more work than I’d like building the palindromes due to single assignment, but nothing too bad. I can see how single assignment will be a pain in some situations though.
The code – - edoc ehT
-module(euler4).
-import(lists).
-export([greatestpalindrome/1]).
greatestpalindrome(N) ->
Greatest = palindrome(N),
io:format("Greatest is ~w", [Greatest]).
palindrome(N) ->
if N >= 100 ->
Candidate = buildpalindrome(N),
Success = testpalindrome(Candidate,999),
if Success == true ->
Candidate;
true ->
palindrome(N-1)
end;
true ->
io:format("no match found~n")
end.
buildpalindrome(N) ->
Nstring = integer_to_list(N),
ReverseN = lists:reverse(Nstring),
Palindrome = Nstring ++ ReverseN,
Npalindrome = list_to_integer(Palindrome),
Npalindrome.
testpalindrome(N,Testfactor) ->
if Testfactor >= 100 ->
if N rem Testfactor == 0 ->
Cofactor = round(N / Testfactor),
if Cofactor >= 100, Cofactor =< 999 ->
true;
true ->
false
end;
true ->
testpalindrome(N,Testfactor - 1)
end;
true ->
false
end.

{ 1 } Trackback
[...] View original here: Project Euler, Problem 4, in Erlang [...]
Post a Comment