#!/usr/bin/perl -w
##############
#
# subroutines ! 
#
# Find the first 1000 primes.
# Don't worry about too much finesse; brute force will do for now.
#
# Class exercise on Sep 25 2003.
# 
# v0.2
#
####################
use strict;
my $VERSION = "0.2";

my $number_of_primes = 40;
my $number_found = 0;
my $x = 2;

while ($number_found < $number_of_primes){
  if (isPrime($x)){
    $number_found++;
    print " " , $number_found, "'th prime = ", $x, "\n";
  }
  $x++;
}

# =========================================================

#
# test isFactor():
#sub testIsFactor {
#  my ($a,$b)=@_;
#  if ( isFactor($a,$b) ){ 
#    print "yes, $a is a factor of $b \n"; 
#  }
#  else {
#    print "no, $a is not a factor of $b \n";
#  }
#}
#testIsFactor(2,10); 
#testIsFactor(5,11);

# returns true if A is a factor of B.
# Usage: if (isFactor(2,10)){ print "yes, 2 is a factor of 10" }
sub isFactor {
  my ($a, $b) = @_;
  my $answer;
  # figure out answer...
  if ( $b % $a == 0 ){
    $answer = 1;
  }
  else {
    $answer = 0;
  }
  return $answer;
}

# test isPrime
# print "11 is prime \n" if isPrime(11);
# print "16 is not prime\n" if not isPrime(16);

# return true if input is prime.
# Usage: print "7 is prime" if isPrime(7);
sub isPrime {
  my ($x) = @_;
  for my $possible_factor (2..sqrt($x)){
    if ( isFactor($possible_factor,$x) ){
      return 0;
    }
  }
  return 1;
}
