Skip to content

Instantly share code, notes, and snippets.

@dzyubam
Created March 20, 2011 00:53
Show Gist options
  • Save dzyubam/877960 to your computer and use it in GitHub Desktop.
Save dzyubam/877960 to your computer and use it in GitHub Desktop.
Project Euler Problem 36
-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.
@t0yv0
Copy link

t0yv0 commented Mar 20, 2011

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment