Created
June 17, 2014 01:10
-
-
Save brendanashworth/8d5ed6a283b82446d81b to your computer and use it in GitHub Desktop.
Collatz conjecture for Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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