Skip to content

Instantly share code, notes, and snippets.

@mrklein
Created May 18, 2012 23:54
Show Gist options
  • Save mrklein/2728223 to your computer and use it in GitHub Desktop.
Save mrklein/2728223 to your computer and use it in GitHub Desktop.
Project Euler #44
#load "euler.cma";;
open Euler;;
let pentagonal n = n * (3*n - 1) / 2;;
let pentagonal_index n = int_of_float ((1. +. sqrt(1. +. 24. *. float_of_int(n))) /. 6.);;
let is_pentagonal d = (mod_float ((sqrt(24. *. float_of_int(d) +. 1.) +. 1.) /. 6.) 1.) = 0.;;
let get_pentagonals n = List.rev_map (pentagonal) (range n);;
let low_pentagonals n =
let idx = pentagonal_index n in
get_pentagonals (idx-1);;
let rec search_pentagonal l = match l with
[] -> raise Not_found
| h :: t ->
let low = low_pentagonals h in
let sums = List.filter (fun x -> is_pentagonal (h + x)) low in
let good = List.filter (fun x -> is_pentagonal (h - x)) sums in
if List.length good > 0 then
(h, good)
else
search_pentagonal t;;
let _ =
let r = search_pentagonal (get_pentagonals 3000) in
let num = fst(r) in
let list = snd(r) in
List.rev_map (fun x -> Printf.printf "%d\n" x) (List.rev_map (fun x -> num - x) list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment