#!/usr/bin/perl
#
# Usage: nextprime <number> [howmany]
#
# Returns the smallest prime greater or equal to argv[1].
# Public domain. Make sure that samuel and factorint are in your PATH.

require "open2.pl";
die "Usage: $0 <number> [howmany]\n"
	unless ($#ARGV >= 0 && $#ARGV <= 1);
$n = shift;
$n = 1 unless $n =~ /^\+?\d+/;
$howmany = shift;
$howmany = 1 unless $howmany =~ /^\+?\d+/;

&open2(RD1, WR1, "samuel -bZ")   || die;
&open2(RD2, WR2, "factorint -t") || die;
select RD1; $|=1; select RD2; $|=1; select STDOUT; $|=1;

while(1) {
	$n =~ tr/+//d; # remove leading plus
	print WR2 "$n\n";
	chop ($ret = <RD2>);
	if ($ret eq "prime") {
		print "$n\n";
		last unless --$howmany;
	}
	print WR1 "$n+1;\n";
	chop ($n = <RD1>);
}
exit 0;
