hit counter

Timeline

My development logbook

Little Erlang Exercise 4

Problem Definition: Euler Problem 4

Through this exercise, I realised that I can reverse a string using a [::-1] operator. Really cryptic, but yet handy.

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
# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 x 99.
# 
# Find the largest palindrome made from the product of two 3-digit numbers.

def isPalindromic(Num):
  #  For string reversal, pls check this url:
  #
  #    http://www.python.org/doc/2.3.5/whatsnew/section-slices.html

  N = str(Num)
  l = len(N)
  div, mod = divmod(l, 2)
  if mod == 1: # odd
    fh = N[0:l/2]
    sh = N[1+l/2:]
    # print “%s %s” % (fh, sh)
  else:
    fh = N[0:l/2]
    sh = N[l/2:]
  return fh == sh[::-1]


if __name__ == "__main__":
  g = [ x * y for x in xrange(100, 999) for y in xrange(100, 999) ]
  print max(filter(lambda x: isPalindromic(x), g))

Here comes an erlang version. In this rare occasion, erlang runs faster than python. It is probably because, first of all, the list comprehension I used in erlang produces a smaller list. Secondly the test of palindromic is more straightforward in the erlang version.

I will revisit the python version, later, when I get a bit more time.

1
2
3
4
5
6
7
8
9
10
11
-module(p4).
-export([findLargestProduct/0]).

isPalindromic(N) when is_list(N) >
  N == lists:reverse(N).

findLargestProduct() >
  List = [X * Y || X < lists:seq(100, 999),
                   Y < lists:seq(100, 999),
                   isPalindromic(integer_to_list(X * Y))],
  lists:max(List).