#!/usr/bin/perl -w
#
# Usage: 
#    ./testPrime
#

use strict;
#use Math::BigInt;
#use Math::BigFloat;
use integer;
my $DEBUG		=  0;
my $MaxNumbersToTry	=  1e7;
my $notPrime		= 0;

print " Prime number search. \n";
print " Input starting number. Notation '1 000 000 000' is OK; 1e9 is not.\n";
print " Start at ? ";
chomp(my $candidatePrime = <>);
#$candidatePrime = new Math::BigInt (" ".$candidatePrime);
my $candidateMax = $candidatePrime + $MaxNumbersToTry;
$candidatePrime--;

#print " number to start at is " . $candidatePrime . "\n";

print " Working ... ";
do {
  $candidatePrime++;
  #print " trying $candidatePrime \n" if $DEBUG;

  $notPrime = 0;
  # my $largestFactor = new Math::BigFloat $candidatePrime;
  # $largestFactor = $largestFactor->fsqrt();

  my $largestFactor = sqrt($candidatePrime);

  # my $largestFactor = $candidatePrime->bsqrt();
  # my $largestFactor = sqrt( " " . $candidatePrime );
  #print " largest factor to test is " . $largestFactor . "\n";

  #print " sqrt is "  . $largestFactor . "\n";
  #print " rounded is " . $largestFactor-> 

  #for (my $n=2; $largestFactor->fcmp($n) >0 ; $n++){
  for (my $n=2; $n<$largestFactor ; $n++){
    print "    n = $n; candidatePrime % n = " .  ($candidatePrime % $n) . "\n"
      if $DEBUG;
    if ( $candidatePrime % $n == 0 ) {
      print " Setting notPrime=1 \n" if $DEBUG;
      $notPrime=1;
      last;
    }
  }
  print " notPrime = $notPrime \n" if $DEBUG;

  if ($candidatePrime>$candidateMax) {
    print "  OOPS: Iteration limit $MaxNumbersToTry hit.\n"; 
    print "        Bailing out at candidate = $candidatePrime \n";
    exit;
  }

} while $notPrime;

print "done.   *** $candidatePrime *** is prime. \n";
