Hailstone sequence: Difference between revisions
Content added Content deleted
m (→{{header|OCaml}}: num_of_int x -> Int x, more readable) |
m (→{{header|OCaml}}: indentation) |
||
Line 214:
=={{header|OCaml}}==
<lang ocaml>#load "nums.cma";;
open Num;;
(* generate Hailstone sequence *)
let hailstone n =
let one = Int 1
and two = Int 2
and three = Int 3 in
let rec g s x =
g [ ] (Int n);;▼
if x =/ one
then x::s
else g (x::s) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
;;
(* compute only sequence length *)
let haillen n =
let one = Int 1
and two = Int 2
and three = Int 3 in
let rec g s x =
g 0 (Int n);;▼
if x =/ one
then s+1
else g (s+1) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
;;
(* max length for starting values in 1..n *)
let hailmax =
let rec g idx len = function
| 0 -> (idx, len)
let a = haillen i in▼
| i ->
if a > len then g i a (i-1) else g idx len (i-1) in▼
▲ let a = haillen i in
g 0 0;;▼
if a > len
then g i a (i-1)
in
;;
hailmax 100000 ;;
(* - : int * int = (77031, 351) *)
List.rev_map string_of_num (hailstone 27) ;;
(* - : string list =
|