bnghtz

prime_1000thprime_diff_eq_9000.pl

Oct 8th, 2014
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.64 KB | None | 0 0
  1. #! /usr/bin/perl
  2.  
  3. # Is there a prime wich after the 1000th prime is exactley bigger by
  4. # 8000 / 9000 / 10000?
  5. # 1000th_prime - prime == 8000 / 9000 / 10000;
  6.  
  7. use strict;
  8. use warnings;
  9.  
  10. sub prime($) {
  11.   my $number = shift;
  12.   return 1 if ($number == 2);
  13.  
  14.   my $d = 2;
  15.   my $sqrt = sqrt($number);
  16.  
  17.   while (1) {
  18.     return 0 if ($number % $d == 0);
  19.  
  20.     if ($d < $sqrt) {
  21.       $d++;
  22.     } else {
  23.       return 1;
  24.     }
  25.   }
  26. }
  27.  
  28. my @res;
  29. for (my $diff = 8000; $diff <= 10000; $diff += 1000) {
  30.     # find a prime, call it 1st
  31.     my $first = 1;
  32.  
  33.     OUTER: while (1) {
  34.       $first += 2;
  35.       next unless prime($first);
  36.  
  37.       # find the 1000th prime ($next) to the 1st prime
  38.       my $last = $first;
  39.       my $next = 0;
  40.      
  41.       while (1) {
  42.         $last += 2;
  43.         next unless prime($last);
  44.         $next++;
  45.  
  46.         # check the 1000th prime
  47.         if ($next == 1000) {
  48.           printf("%-40s", "1000th prim after $first = $last");
  49.           my $difference = $last - $first;
  50.          
  51.           # if it fit, search is over :)
  52.           if ($difference == $diff) {
  53.             print "I FOUND IT! " x 3 . "\n";
  54.             push(@res, "$diff == $first-$last ($next.)\n");
  55.             last OUTER;
  56.           }
  57.           # if it's too big, search is over
  58.           elsif ($difference > $diff) {
  59.             print "difference is too big    $difference\n";
  60.             last OUTER;
  61.           }
  62.           # if it's too small, get a bigger 1st prime!
  63.           else {
  64.             print "difference is too small  $difference\n";
  65.             last
  66.           }
  67.        }
  68.     }
  69.   }
  70. }
  71.  
  72. print "\n" x 2 . join('',@res);
Advertisement
Add Comment
Please, Sign In to add comment