Jump to content

Hailstone sequence: Difference between revisions

m
m (→‎{{header|OCaml}}: num_of_int x -> Int x, more readable)
m (→‎{{header|OCaml}}: indentation)
Line 214:
 
=={{header|OCaml}}==
<lang ocaml>#load "nums.cma";;
#load "nums.cma";;
open Num;;
 
(* generate Hailstone sequence *)
let hailstone n =
let one = Int 1 and two = Int 2 and three = Int 3 in
and two = Int 2
let rec g s x = if x =/ one then x::s else
and three = Int 3 in
g (x::s) (if mod_num x two =/ one then three */ x +/ one else x // two) 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
g [ ] (Int n);;
;;
 
(* compute only sequence length *)
let haillen n =
let one = Int 1 and two = Int 2 and three = Int 3 in
and two = Int 2
let rec g s x = if x =/ one then s+1 else
and three = Int 3 in
g (s+1) (if mod_num x two =/ one then three */ x +/ one else x // two) 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
g 0 (Int n);;
;;
 
(* max length for starting values in 1..n *)
let hailmax =
let rec g idx len = function 0 -> (idx, len) | i ->
| 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)
if a > len then g i a (i-1) else g idx len (i-1) in
in
g 0 0;;
;;
 
hailmax 100000 ;;
(* - : int * int = (77031, 351) *)
 
List.rev_map string_of_num (hailstone 27) ;;
 
(* - : string list =
Cookies help us deliver our services. By using our services, you agree to our use of cookies.