#!/usr/bin/perl -w
##############
#
# 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.1
#
####################
use strict;
my $VERSION = "0.1";
my $DEBUG = 0;
my $repeats = 10;   # do this several times for timing accuracy
my $desired_number_of_primes = 200;

# my $start_time = time();

my @primes;      # list of prime numbers. 

# for (1..$repeats){

@primes = ();

my $possible_prime = 2;           # let's start here looking for primes.
my $still_looking_for_primes = 1;
while ($still_looking_for_primes){
  print " starting to look at possible_prime = $possible_prime \n" if $DEBUG;

  # for each integer $possible_factor = 2 .. ($possible_prime-1)
  # if $possible_factor divides $possible_prime, then it isn't prime.
  # go to next number

  my $is_prime = 1;                                  # assume is prime
  for (my $possible_factor = 2;			     # look at factors
       $possible_factor < sqrt($possible_prime);
       $possible_factor++){
    print "   testing possible_factor = $possible_factor \n" if $DEBUG;
    if ( $possible_prime % $possible_factor == 0 ){  #  find divisor
      $is_prime = 0;                                 #  not prime
      print "     factor found\n" if $DEBUG;
      last;                                          #  stop doing this loop
    }
  }
  if ($is_prime){
    print " adding $possible_prime to list of primes\n" if $DEBUG;
    push @primes, $possible_prime;
  }

  $possible_prime++;                                 # look at next number
  if ( scalar @primes >= $desired_number_of_primes ) {
    $still_looking_for_primes = 0;
  }
}

# }  # repeats

# print " start_time = $start_time \n";
# print " time() = ", time(), "\n";

print "Here is the $desired_number_of_primes-th prime: ", pop @primes, "\n";

# print "Elapsed time once through = " , (time()-$start_time)/$repeats, "\n";
