text: If you been following me the last three times I've done this, then you really don't need any introductions.
  Problem four is as follows:
  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  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.
  And my results in the usual three languages are:
  Hase . filter is_palimdrome $ zipWith (*) y z where y = [1000,999..100] z = [1000,999..100]
  Python:
  #!/usr/bin/python def int_to_list(number): return map(int, str(number)) def is_palindrome(number): local_list = int_to_list(number) return local_list == list(reversed(local_list)) if __name__ == "__main__": second_list = first_list = list(reversed(range(100,1000+1))) prod_set = map(lambda i,j: i*j, first_list, second_list) print "%s" % max(filter(is_palindrome,prod_set))
  And finally, Perl:
  #!/usr/bin/perl use strict;use warnings;use List::MoreUtils qw(pairwise); sub is_palimdrone{ my ($number) = @_; my @digits = split(//, $number); my @reversed_digits = reverse(@digits); for (my $i = 0; $i < @digits; $i++) { return 0 if $digits[$i] != $reversed_digits[$i]; } return 1;} my @two = my @one = reverse((1..1000)); my @join = pairwise { $a * $b } @one, @two; foreach(@join){ if ( is_palimdrone($_)) { print "$_\n"; last; }}
  Run Times
  Haskell: 0m0.034s
  Python: 0m0.060s
  Perl: 0m0.166s
  For anyone that is not aware, haskell should win this statistic every time. Out of the three languages its the only one that is compiled. If anyone knows of a way to run haskell interpretively, and without using ghci, please let me know. I've tried looking on the internets for this piece of information, but have come up short.
  I am still open to code suggestions or improvements. I have found these to be very helpful and useful. So thank you to everyone that has said something before.
  UPDATE
  So here is the new code that fixes the problem of my algo before. I'm leaving the old up just to future readers aren't confused.
  Thanks goes out to Jeremiah, Tom.B, Juster, and Guillaume for the code ideas used to fix the mistakes in the code above. Thanks guys!
  Has $ [ x * y | x <- nums, y <- nums, is_palimdrome (x * y)] where nums = [1000,999..100]
  #!/usr/bin/python def int_to_list(number): return map(int, str(number)) def is_palindrome(number): local_list = int_to_list(number) return local_list == list(reversed(local_list)) if __name__ == "__main__": print "%s" % max([x * y for x in range(1000,100, -1) \ for y in range(1000,100,-1) \ if is_palindrome(x * y)])
  #!/usr/bin/perl use strict;use warnings;use List::Util qw(max); sub is_palimdrone{ my ($number) = @_; my @digits = split(//, $number); my @reversed_digits = reverse(@digits); for (my $i = 0; $i < @digits; $i++) { return 0 if $digits[$i] != $reversed_digits[$i]; } return 1;} my @two = my @one = reverse((100..999));my @three; for my $one (@one){ for my $two (@two) { my $three = $two * $one; next unless is_palimdrone($three); push @three, $three; }} print max(@three);
  Console.WriteLine(Enumerable.Range(100, 900).Select(n => new {left = n, right = Enumerable.Range(100, 900)}).SelectMany(m => m.right.Select(o => o*m.left)).Where(a => new String(a.ToString().Reverse().ToArray()) == a.ToString()).Max());
  Thank you for the comment, what language is that in?
  #include <stdio.h>#include <string.h>#include <stdbool.h> bool is_palindrome(int const n){ unsigned int cum = 0; unsigned int n2 = n; while(n2 > cum) { cum *= 10; cum += n2 % 10; n2 /= 10; } return n2 == cum;} unsigned int find_palindrome(){ unsigned int max_palin = 0; unsigned int minj = 99; for(unsigned int i = 999; i > 99; i--) { if(i*i < max_palin) { break; } for(unsigned int j = i; j > minj; j--) { unsigned int const new_palin = i*j; if(is_palindrome(new_palin)) { minj = j; if(new_palin > max_palin) { max_palin = new_palin; } break; } } } return max_palin;} int main(){ unsigned int const max = find_palindrome(); printf("%d\n",max); for(unsigned int i = 0; i < 10000; i++) { unsigned int const max = find_palindrome(); }}
  def find_palindrome(): max_palin = 0 minj = 99 for i in xrange(999,99,-1): if i*i < max_palin: # because new tested values are less or equal i*i, we can stop # because their is no palindrom that is bigger that the current one break # iter between i and minj for j # - i because it useless to have a value of j which is bigger than i (we # allready tested that case) # - to minj because the last founded palindrom was (i+n) * minj, so i * # min_j is smaller for j in xrange(i, minj, -1): # the is_palindrom test as been inline because it is quite simple # and give really good speed new_palin = i*j s = str(new_palin) if s == s[::-1]: minj = j max_palin = max(new_palin, max_palin) # We can shortcut the loop, because with that value of i, it is # useless to test lower values of j break return max_palin if __name__ == '__main__': import timeit print find_palindrome() # return the time of one run, tested for 10000 runs print timeit.Timer('find_palindrome()','from __main__ import find_palindrome').timeit(10000) / 10000
  times:
  C
  % 14:54 guillaume@guillaume-desktop ~ gcc -std=c99 -O3 -march=native palindrom.c
  % 14:54 guillaume@guillaume-desktop ~ time ./a.out
  906609
  ./a.out 0.87s user 0.01s system 100% cpu 0.878 total
  ie ~0.08ms / run
  Python
  % 14:16 guillaume@guillaume-desktop ~ time python palindrome.py
  0.00366615915298
  python palindrome.py 3.68s user 0.00s system 99% cpu 3.687 total
  for 1000 runs, ie, 3ms / run
  Pypy
  % 14:17 guillaume@guillaume-desktop ~ time pypy palindrome.py
  0.00065650241375
  ~/src/pypy/pypy-1.3/bin/pypy palindrome.py 6.56s user 0.01s system 99% cpu 6.576 total
  for 10000 runs, ie ~0.6ms runs.
  #!/usr/bin/pythonimport time, psyco psyco.full() def is_palindrome(number): local_list = "%s"%number local_list1 = list(local_list[:]) local_list1.reverse() return local_list == "".join(local_list1) def main(): maxVal=0 for x in range(1000,100, -1): for y in range(1000,100,-1): if is_palindrome(x * y): maxVal = max(x * y, maxVal) return maxVal if __name__ == "__main__": t1 = time.time() print main() print time.time() - t1
  Hey Darrell, thanks for joining the conversation.
  I will admit that your code it is a lot faster. However, your code is also producing the wrong answer. If it makes you feel better I was getting the same answer when I first started this problem and in playing around with things a little more I realized it. These puzzles are kind of tricky that way. ;) If you take a second to read through the comments you should get a pretty strong hint on how to fix it.
  Why are you saying that his code is false. For me it gives the right answer which is 906609.
  But by the way I'm still does not understand why:
  1) Every one iter in reverse. If you evaluate all the possibilities, the order of iteration does not change anything.
  2) Why everyone writes really complex is_palindrom function when the really simple I proposed one week ago is faster ;)
  I said what I said because when I copied his code, I got 580085 as my answer. I might have copied it wrong. (I'm not able to check at the moment, I will when I get home.)
  And I totally agree with you Guillaume, your is_palindrome function is as concise as it could possibly be. I know I wrote mine out that way because I wasn't aware of being able to reverse a string with a simple [::-1]. I can't speak for everyone else, but that is certainly going into my python toolbox.
  To convert numbers to a list, I just abused show:
  isPalindrome n = n == (read (reverse (show n))::Int)solution = maximum [ a * b | a <- [100..999], b <- [a..999], isPalindrome (a * b) ]
  Your isPalindrome function is rather nice Bro! Looks to be a greatly more efficient way of doing the reverse check than what I have. Going to have to remember this method. :)
  Hey mate,
  There's a subtle optimisation in my solution that I can't see in anyone else's so far. Can you see it? :)
  I did a series of blog posts about Euler #4 in Perl:
  *
  *
  *
  First post pulls in Clojure, Python & Ruby examples as well.
  /I3az/
  Like my python optimisation you don't use in the post update, there is a way to optimise is_palindrome in haskell:
  is_palimdrome number = num_list == reverse num_list where num_list = show number
  @home, it runs five time quicker.
  Now for the main loop:
  find_palindrome :: Int -> Int -> Int -> Int -> Intfind_palindrome current_max minj i j | is_palimdrome number = find_palindrome (maximum [current_max,number]) j (i-1) (i-1) | j == minj = find_palindrome current_max minj (i-1) (i-1) | i == 99 = current_max | otherwise = find_palindrome current_max minj i (j-1) where number = i*j main :: IO ()main = print (find_palindrome 0 99 999 999)
  It's the first time I wrote haskell of my life, so some stuff may be wrong, but I win ten times the speed ;)
  You seem to be picking up Hasekll pretty quickly. Congratulations! You palindrome does look to be much faster than mine. I can't help but feel that is the haskell translation of the Python code you submitted in your first post.(Not trying to be insulting, just stating an observation.)
  I didn't just copy your previous code because I need to figure this stuff out for myself (Haskell especially) and just blindly copying code doesn't allow me to learn anything. So I look at the code that everyone has shared and then I try to incorporate into mine.
  Hello again.
  The code I suggested yesterday, ie:
  def is_palindrome(number): s = str(number) return s == s[::-1] print max((i*j,i,j) for i in range(100,1000) for j in range(100,1000) if is_palindrome(i*j))
  can really be upgraded, like that :
  def find_palindrome(): max_palin = 0, (0,0) minj = 99 for i in xrange(999,99,-1): for j in xrange(i-1, minj, -1): if is_palindrome(i*j): minj = j max_palin = max((i*j, i, j), max_palin) return max_palin
  Currently I get 5ms / run (median of 1000 run with timeit) with python2. It drops to 4ms / run if I inline the is_palindrome function.
  with pypy 1.3 it drops to 1.4 ms without inline and 0.9 ms with inline.
  Note: quad core i7 here, but only one core used.
  There is still room for improvment.
  Use xrange(i, minj, -1) to allow square values to be evaluated
  juster,
  shift @a;
  It's a great idea, I didn't see it
  I added a Benchmark module in order to avoid the interpreter startup
  Thank niceperl. My solution was pretty much the same as yours other than that. In my script I'm not sure if only looping from 900 to 999 is fair. Owell it's all for fun. I'm glad we represented perl.
  Sadly there is an error in my code. I should not have modified the array while looping over it with for. Instead it is better to make two copies of the array, one for the inner and one for the outer loop. The for loop in my post actually skips every other number. Let this be a warning to others!
  Thanks Bryce for being brave enough to post code on your blog and be open to suggestions. I must also thank you for fixing the perl codetags and getting me hooked on project euler! The number theory is very fun.
  Thanks for that comment Juster!! Its not everyday that I get a comment like that.
  And you might want to wait a little while before you thank me for introducing you to Project Euler. In a couple of months you might be cursing my name for the same reason after losing sleep to solve problems and the like. ;)
  I agree this number theory stuff is fun, its a great way to stretch your normal programming patterns. I'm glad your starting to enjoy it.
  Just another perl hacker, here. You should not use List::MoreUtil's "pairwise" for this problem. What you want instead is something similar to the cartesian product of the two sets of numbers. Pairwise shifts each array, and operates on those two elements. When using pairwise you can only find palindromes made out of squares.
  My solution doesn't check the same product twice and also uses Jeremiah's trick to only check between 900-999. It's a little faster than niceperl's because of these tricks. Niceperl's is the only other perl example that gives the correct answer.
  my @nums = reverse 900..999;for my $x ( @nums ) { shift @nums; # <-- don't check things twice for my $y ( @nums ) { my $z = $x * $y; next unless $z eq reverse $z; print "$x * $y = $z\n"; exit 0; }}
  PS why is there no perl sourcecode tag? I had to use ruby. :(
  Hey juster,
  Thanks for posting.
  First off I'll look into the Perl source tags problem and thanks for saying something.
  I also agree with what your saying regarding pairwise. It was a flaw in my logic (in all 3 languages ). I programmed Perl to work similarly to what you wrote. But I ended up changing it because I thought this was a more clever way of doing it. Turns out that ultimately I should have stuck with the original idea for Perl.
  Thanks again for the comment and sharing of your code.
  Just as a quick update to my own post. I have fixed things so that both the perl & haskell code tags work. Again thanks Juster for saying something.
  use strict;
  use Benchmark ':hireswallclock';
  sub main {
  my ($r, $p, $a, $b) = (0, 0);
  my @a = reverse (100..999);
  A: foreach $a(@a) {
  foreach $b(@a) {
  $r = $a * $b;
  next A if( $r <= $p );
  $p = $r if $r eq reverse($r);
  }
  }
  print $p, "\n";
  }
  my $t = timeit(1, 'main');
  print timestr($t),"\n";
  #results (on my laptop): 0.00717092 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU)
  Faster variant
  def is_palindrome (number):
  n = str (number)
  if n [0] != n [-1]:
  return False
  n = n [1:-1]
  while len (n)>1 and n[0]==n[-1]:
  n = n [1:-1]
  return len (n) <= 1
  I'm not sure I quite understand your problem, but
  1) is_palindrom can be writed like
  #!/usr/bin/python
  def is_palindrome(number):
  s = str(number)
  return s == s[::-1]
  2) your algo is false, you only find the square of a number of three digits that is palindrome. The real answer is 906609 = 993 x 913
  it can be found with this trivial algo:
  print max((i*j,i,j) for i in range(100,1000) for j in range(100,1000) if is_palindrome(i*j))
  Here :
  real 0m4.293s
  user 0m2.316s
  sys 0m0.029s
  3) quicker with
  print max((i*j,i,j) for i in xrange(100,1000) for j in xrange(i+1,1000) if is_palindrome(i*j))
  Hi Guillaume,
  After looking at what you posted I have to agree with you that I did get my algo wrong. Using your examples I see where I made my mistakes and I will fix them shortly.
  Thanks also for the python code posted. I think incorporating both your second solution with Tom's range(1000,100,-1) technique would be more efficient in finding the highest palindrome numeral.
  Thanks again for posting and sharing. I appreciate it!
  But I'm wondering, why are your iterating in reverse order ?
  You can assume that the number is closer to the top of the range. For two digit numbers it is 9009 = 91 × 99. So if you start with 99x99, it will take fewer tests than starting with 10x10.
  Yes, but this does changes nothing in this code, because all the options are evaluated.
  Unless a requirement is missing, I believe your code is incorrect. The code given is calculating perfect squares, then finding the largest one that's a palindrome.
  It's giving 698896, which is 836*836, but the answer should be 993*913 = 906609.
  Calculated using this Python code:
  #!/usr/bin/python def is_palindrome(number): return str(number) == str(number)[::-1] if __name__ == "__main__": # Assumes that the largest palindrome will be created by two numbers in the range 900-1000 print('{}*{} = {}'.format(*max((i,j,i*j) for i in range(1000, 900, -1) for j in range(1000, 900, -1) if is_palindrome(i*j))))
  Simple fix for the Haskell:
  main :: IO ()main = print . maximum $ [x*y | x <- nums, y <- nums, is_palimdrome (x*y)] where nums = [1000,999..100]
  The version below is faster as it avoids duplicate numbers in the list comprehension. Also since 1000 is a 4 digit number and the problem states "... product of two 3-digit numbers" then nums = [999, 998..100]
  giving
  main :: IO ()main = print . maximum $ [x*y | x <- nums, y <- nums, x >= y, is_palimdrome (x*y)] where nums = [999, 998..100]
  Hey Jeremiah, thanks for the code posts. Both the Python & Haskell code snippets.
  I tried using your python code, but I had issues. So I just copied your list comprehension from your haskell code and translated it to python and put it there.
  Thanks again for sharing!
  For the Python example, line 11 could be:
  second_list = first_list = range(1000, 99, -1)
  second_list = first_list = range(1000, 99, -1)
  That should be faster than creating the initial list (call to range), creating an iterator that reverses the values, then converting that iterator to another list. I'm not sure how significant (if at all) the difference would be, but it's probably worth testing.
  Also I'm curious to know why you used 2 different references to the same list (first_list and second_list) instead of just 1 (map can take the same argument multiple times). Since it's still the same list I doubt there would be any appreciable performance penalty, but it's also unnecessary code IMHO.
  Other than that, neat examples!
  Hey Tom,
  Thanks for the post and also thanks for the way to use range backwards. Its one of those pieces of code that after looking at it I slapped my hand to my forehead because its simple enough that I should have been able to figure it out on my own yet didn't.
  I'll incorporate this change into my next revision, as it has to be more efficient than creating a range and then revering it.
  In fact, your entire problem can be expressed as:
  use strict;
  use warnings;
  use List::MoreUtils qw(pairwise);
  use List::Util qw(first);
  my @nums = reverse 100 .. 999;
  print first { $_ eq reverse $_ } pairwise { $a * $b } @nums, @nums;
  sub is_palimdrone { $_[0] eq reverse $_[0] }
  is far shorter and neater :)
  Hey Paul,
  Thanks for the comment also that is a much cleaner version of palindrome verification than both of our code. Also, as mentioned by Juster above and in regards to your previous comment, pairwise isn't a good function to use for this problem because it manipulates $a and $b together. so you get 1000 * 1000, 999 * 999, etc. Instead of the needed 1000 * 999.
  Thanks again for the code submittal!
  If you made it this far down into the article, hopefully you liked it enough to share it with your friends. Thanks if you do, I appreciate it.