Hello all,

I have prepared a code to generate Collatz sequences based on the even
(n/2) and odd ((3n+1)/2) rules.

clear

function [ns, seq] = collatz(n)
// Reference: https://en.wikipedia.org/wiki/Collatz_conjecture
//ns =number of steps; seq=Collatz sequence
seq(1) = n;
// Position an index on the next element of the sequence
i = 2;

// Repeat the iteration until you find a 1
while seq(i-1) ~= 1
    // Use modulo to define even/odd numbers
    if modulo(seq(i-1), 2) == 0
        // Step taken if even
        seq(i) = seq(i-1)/2;
    else
        // Step taken if odd
        // seq(i) = 3*seq(i-1) + 1 // "3n+1 Collatz"
        seq(i) = (3*seq(i-1) + 1)/2; // "shortcut form Collatz"
    end
    // Increment index
    i = i+1;
end
// Find the length of the sequence
ns = length(seq);
endfunction

n = input('Enter a positive integer: ')
tic()

for  i = 1:n
   [nsi, seqi] = collatz(i);
   ns(i) = nsi;
   seq(1:nsi, i) = seqi;
end

// Find maxima in each Collatz sequence
peak_values = max(seq, 'r')

t=toc()
mprintf('Elapsed time: %4.8f\n',t)

What I would like to try is apply a further rule to generate a plot
based on the Collatz sequences using left/right angular turn depending on
whether the number is odd or even, going in reverse (starting at 1) and
branching out.

I can easily define the odd/even numbers in the sequence (modulo), but not
sure how to
apply the angle rotation for the graphic plot. Any pointers would be
helpful.

Attached an example image by way of reference.

On a secondary point, the Collatz conjecture can be applied to negative
values, but would be interested to know how the code has to be tweaked. If
you stick a negative value in the code as is, it gets stuck in a loop.

Thanks
Lester
_______________________________________________
users mailing list
users@lists.scilab.org
http://lists.scilab.org/mailman/listinfo/users

Reply via email to