Skip to content

Instantly share code, notes, and snippets.

@brendanashworth
Created June 17, 2014 01:10
Show Gist options
  • Save brendanashworth/8d5ed6a283b82446d81b to your computer and use it in GitHub Desktop.
Save brendanashworth/8d5ed6a283b82446d81b to your computer and use it in GitHub Desktop.
Collatz conjecture for Perl
#!/usr/bin/perl
# This script finds the number of cycles necessary to get to 1 via the
# Collatz conjecture.
use strict;
use warnings;
unless (defined $ARGV[0]) {
print("Supply the integer as the first argument.");
exit;
}
my $i = $ARGV[0];
my $steps = 0;
while ($i != 1) {
$steps++;
# is even
if ($i % 2 == 0) {
$i = $i / 2;
} else {
# is odd
$i = ($i * 3) + 1;
}
}
print("Done. Took " . $steps . " to bring " . $ARGV[0] . " to 1.\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment