Skip to content

Instantly share code, notes, and snippets.

@jbobbylopez
Created October 11, 2011 04:30
Show Gist options
  • Save jbobbylopez/1277279 to your computer and use it in GitHub Desktop.
Save jbobbylopez/1277279 to your computer and use it in GitHub Desktop.
My attempt at calculating prime numbers in perl, without loops, using recursion.
#!/usr/bin/env perl
# Just a little code to test for prime numbers
# Originally posted to my blog at www.jbldata.com
use strict;
use warnings;
use 5.010;
$DB::deep = 500;
$DB::deep = $DB::deep; # Avoids silly 'used only once' warning
no warnings "recursion";
# Identify primes between ARG0 and ARG1
my ($x, $y, $re_int, $result);
my ($prime, $is_int);
$x = $ARGV[0];
$y = $ARGV[1];
$is_int = sub {
my $re_int = qr(^-?\d+\z);
my ($x) = @_;
$x =~ $re_int
? 1
: 0;
};
$prime = sub {
my ( $x, $y ) = @_;
if ( $y > 1 ) {
given ($x) {
when ( $is_int->( $x / $y ) ) {
return 0;
}
default {
return $prime->( $x, $y - 1 );
}
}
}
else { return 1; }
};
$result = sub {
my ( $x, $y ) = @_;
if ( $x <= $y ) {
if ( $prime->($x, $x-1) ) {
say $x;
}
$result->( ( $x + 1 ), $y );
}
};
$result->($x, $y);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment