Sunday, July 18, 2010

Problem 45: After 40755, what is the next triangle number that is also pentagonal and hexagonal?

Here we reused the technique from Problem 44 for quickly asserting that a number is in the range of a function by verifying that n = f (f-1(n)).  We could also have tested that f-1(n) is integral.

let problem45a =
    let pent n = n*(3L*n-1L)/2L
    let pentInv n = (1L + sqrtL(24L*n + 1L))/6L
    let isPent n = (n = (pent (pentInv n)))
    
    let hex n = n*(2L*n-1L)
    let hexInv n = (1L + sqrtL(8L*n + 1L))/4L
    let isHex n = (n = (hex (hexInv n)))
    
    let tri n = n*(n+1L)/2L
    let rec triSeq n = seq {yield tri n; yield! triSeq (n+1L)}
    
    triSeq 286L
    |> Seq.find (fun n -> isPent n && isHex n)

No comments:

Post a Comment