#!/usr/bin/perl
####################
#
# Find and print prime numbers.
# Demo of Sep 14 assignment for web perl course.
#
# Jim Mahoney
# v 0.1 September 6
####################
use strict;
use warnings;

### testing isPrime()
for my $prime (7,31,59){
  isPrime($prime) == 1 or die "oops: isPrime($prime) is false";
}
for my $isnt_prime (6,10,21,55){
  isPrime($isnt_prime) == 0 or die "oops: isPrime($isnt_prime) is true";
}
### end tests


# Check each of a sequence of numbers to see if they're prime.
my ($min_number, $max_number) = (2, 200);
print " Prime numbers from $min_number .. $max_number : \n";
for my $number ( $min_number .. $max_number ){
  print  "  $number \n" if isPrime($number);
}
print "Done.\n";
exit;

# --- subroutines --------------------------------

# $boolean = isPrime($number)
# Given a number, return 1 or 0 (true or false) if it's prime or not.
#   The algorithm used is particularly simple:
#   I just try to divide each possible factor from 2 up to half of the number.
#   Note that "%" is the binary "mod" operator, so that for example 
#   10 % 3 = 1 since the remainder of 10/3 is 1.
sub isPrime {
  my ($candidate) = @_;
  my ($min_factor, $max_factor) = (2, $candidate/2);
  for my $factor ($min_factor .. $max_factor){
    return 0 if 0 == $candidate % $factor;    # Has a factor, so not prime.
  }
  return 1;                                   # No factors, so it's prime.
}
