blob: 9db105e1144751230b78c750f00c7145bc2ca667 (
plain)
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
|
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use feature qw{ postderef say signatures state switch };
no warnings qw{ experimental recursion };
binmode( STDOUT, ":utf8" ) ;
use Carp;
use JSON;
my $json = JSON->new->canonical->pretty->allow_nonref;
my $n = 23;
my @output = collatz($n);
say join ' → ', @output;
exit;
sub collatz ( $n ) {
$n = int $n;
croak if $n < 1;
my @sec;
if ( $n == 1 ) {
push @sec, 1;
}
elsif ( $n % 2 == 1 ) { #odd
my $o = ( 3 * $n ) + 1;
push @sec, $n, collatz($o);
}
elsif ( $n % 2 == 0 ) { #even
my $o = $n / 2;
push @sec, $n, collatz($o);
}
return wantarray ? @sec : \@sec;
}
|