1 people like it.

Imperative and simple version for Collatz Conjecture or 3n + 1 Problem

Imperative and simple version for Collatz Conjecture or 3n + 1 Problem

 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: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
//https://en.wikipedia.org/wiki/Collatz_conjecture
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36

//3n + 1 Problem (printing all)
let min a b = if (a > b) then b else a
let max a b = if (b > a) then b else a
let f a b = 
    for j = (min a b) to (max a b) do
        let mutable i = j
        while (i > 1) do
            printf "%d " i
            if ((i % 2) = 0) then i <- i / 2 else i <- 3 * i + 1 
        printfn "1"
(*

> f 1 10;;
1
2 1
3 10 5 16 8 4 2 1
4 2 1
5 16 8 4 2 1
6 3 10 5 16 8 4 2 1
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
8 4 2 1
9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
10 5 16 8 4 2 1
val it : unit = ()

*)

//3n + 1 Problem (counting max)
let min a b = if (a > b) then b else a
let max a b = if (b > a) then b else a
let f a b = 
    let mutable max_length = 1
    for j = (min a b) to (max a b) do
        let mutable i = j
        let mutable count = 1
        while (i > 1) do            
            count <- count + 1
            if ((i % 2) = 0) then i <- i / 2 else i <- 3 * i + 1
        max_length <- (max max_length count)
    max_length
(*

> f 1 10;;
val it : int = 20
> f 100 200;;
val it : int = 125
> f 201 210;;
val it : int = 89
> f 900 1000;;
val it : int = 174

*)
val min : a:'a -> b:'a -> 'a (requires comparison)

Full name: Script.min
val a : 'a (requires comparison)
val b : 'a (requires comparison)
val max : a:'a -> b:'a -> 'a (requires comparison)

Full name: Script.max
val f : a:int -> b:int -> unit

Full name: Script.f
val a : int
val b : int
val j : int
val mutable i : int
val printf : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printf
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val f : a:int -> b:int -> int

Full name: Script.f
val mutable max_length : int
val mutable count : int
Raw view New version

More information

Link:http://fssnip.net/7OH
Posted:1 years ago
Author:Fabio Galuppo
Tags: imperative