-
Notifications
You must be signed in to change notification settings - Fork 0
/
004-largest-palindrome-product.lhs
executable file
·51 lines (35 loc) · 1.21 KB
/
004-largest-palindrome-product.lhs
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env runhaskell
[Largest palindrome product](http://projecteuler.net/problem=4)
---------------------------------------------------------------
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.
Idea
----
Generate the pairs in the following order to assure (decreasing) monotonicity:
999 * 999
999 * 998
998 * 998, 999 * 997
998 * 997, 999 * 996
997 * 997, 998 * 996, 999 * 995
997 * 996, 998 * 995, 999 * 994
...
Code
----
> isPalindromicNumber :: Integer -> Bool
> isPalindromicNumber n = let s = show n
> in s == reverse s
> f :: Integer -> Integer -> Integer -> Integer -> [Integer]
> f l u x y = [ (x + d) * (y - d) | d <- [0 .. min (u - x) (y - l)]]
> g :: Integer -> Integer -> Integer -> [Integer]
> g l u x = f l u x x ++ f l u x (x - 1)
> h :: Integer -> Integer -> [Integer]
> h l u = concatMap (g l u) [u, u - 1 .. l]
> main :: IO ()
> main = let result = head
> $ filter isPalindromicNumber
> $ h 100 999
> in print result
Answer
------
906609