Collatz sequence in Erlang

Viewed 85

The problem that I am trying to solve is as follows: Write an Erlang function named collatz that takes one argument N. You may assume that N is an integer 1 or larger. The function should print the Collatz sequence (one number per line) starting with N. For example, collatz( 4 ) should print 4, 2, 1 (on separate lines). collatz( 6 ) should print 6, 3, 10, 5, 16, 8, 4, 2, 1 (on separate lines).

The collatz function that I have written is working properly but I am having difficulty in printing the output on separate lines. The commented-out part of the code below is my attempt to generate the output on separate lines.

    collatz(1) -> [1];
    collatz(N) when N rem 2 == 0 ->
    [N|collatz(N div 2)];
    %[io:format("Collatz is : ~p~n",[N])N|collatz(N div 2)];
    collatz(N) ->
    [N|collatz(3*N+1)].
    %[io:format("Collatz is : ~p~n",[N])N|colla[N|collatz(N div 2)]tz(3*N+1)].
    

The output that I get when I call for example collatz(5) is [5,16,8,4,2,1]. I want these numbers to be printed out on separate lines.

3 Answers

Instead of running the whole program and printing the result, consider printing each element before each iteration, like

collatz(N) -> io:format("~p~n", [N]), collatz(next_collatz(N)).

You just need to evaluate io:format/2 before prepending N in your list…

collatz(1) ->
    io:format("Collatz is : 1~n"),
    [1];
collatz(N) when N rem 2 == 0 ->
    io:format("Collatz is : ~p~n", [N]),
    [N | collatz(N div 2)];
collatz(N) ->
    io:format("Collatz is : ~p~n", [N]),
    [N | collatz(3 * N + 1)].
1> C = fun C(1,_) -> io:format("1~n") ;
2> % rem is not allowed in a guard, it is why I added it in the parameters                            
2> C(N,0)  -> io:format("~p~n",[N]), NN = N div 2,  C(NN, NN rem 2);
3> C(N,_) -> io:format("~p~n",[N]), NN = 3 * N + 1, C(NN, NN rem 2) end.
#Fun<erl_eval.19.97283095>
4> Collatz = fun(N) -> C(N, N rem 2) end.                               
#Fun<erl_eval.44.97283095>
5> Collatz(5).                                                          
5
16
8
4
2
1
ok
6>
Related