-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve45.hs
37 lines (28 loc) · 1.21 KB
/
solve45.hs
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
-- https://projecteuler.net/problem=45
-- Run with: 'ghc solve45.hs && ./solve45' or 'runhaskell solve45.hs'
-- using Haskell with GHC 8.0.2
-- by Zack Sargent
{- Prompt:
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
-}
{- NOTE: This is a quick and dirty solution.
From the fourm, the use of Diophantine equations could significantly optimize this process. -}
-- Note: All hexagonal numbers have to be triangle numbers
-- so we don't need to check for triangle numbers.
rule n = toInteger (round n)
pentagonalNum n = rule ((n * (3*n - 1))/ 2)
hexagonalNum n = rule (n * (2*n - 1))
find x a b
| x == pentagonalNum a && x == hexagonalNum b = x
| x > pentagonalNum a = find x (a + 1) b
| x > hexagonalNum b = find x a (b + 1)
| x `mod` 2 == 0 = find (x + 1) a b
| otherwise = find (x + 2) a b
findAbove x = find x 5 5
main = print (findAbove 1533700000)
-- -> 1533776805