Created
March 20, 2011 00:53
-
-
Save dzyubam/877960 to your computer and use it in GitHub Desktop.
Project Euler Problem 36
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(euler36). | |
-export([is_palindrome/1, solve/0]). | |
is_palindrome(X) -> | |
integer_to_list(X) =:= lists:reverse(integer_to_list(X)). | |
solve() -> | |
% need to check only odd integers since the even ones will never be palindromes in binary base | |
solve(lists:seq(1, 999999, 2), 0). | |
solve([], Sum) -> | |
Sum; | |
solve([H | Tail], Sum) -> | |
% the last expression below is converting the number to binary base | |
% andalso operator really speeds it up | |
Check = is_palindrome(H) andalso is_palindrome(list_to_integer(hd(io_lib:format("~.2B", [H])))), | |
case Check of | |
true -> solve(Tail, Sum + H); | |
false -> solve(Tail, Sum) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you reduce memory consumption? In Haskell, [1..999999] does not allocate megabytes of memory because the language has lazy evaluation. In your example, however, I am guessing that lists:seq(1, 999999, 2) has to create the whole list immediately! You can thread a number instead.