From d8802f67713951c792b85c955fc1b03526424af9 Mon Sep 17 00:00:00 2001 From: lakpatashi Date: Sun, 16 May 2021 18:19:01 +0530 Subject: Finished challenge-022 ch-1 only with perl --- challenge-022/lakpatashi/README | 1 + challenge-022/lakpatashi/perl/ch-1.pl | 58 +++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 challenge-022/lakpatashi/README create mode 100755 challenge-022/lakpatashi/perl/ch-1.pl diff --git a/challenge-022/lakpatashi/README b/challenge-022/lakpatashi/README new file mode 100644 index 0000000000..bc153bd576 --- /dev/null +++ b/challenge-022/lakpatashi/README @@ -0,0 +1 @@ +Solution by lakpatashi diff --git a/challenge-022/lakpatashi/perl/ch-1.pl b/challenge-022/lakpatashi/perl/ch-1.pl new file mode 100755 index 0000000000..d6108c3fbb --- /dev/null +++ b/challenge-022/lakpatashi/perl/ch-1.pl @@ -0,0 +1,58 @@ +#!/usr/bin/perl +use POSIX; +use strict; +use warnings; +use List::Util qw( min max sum); +use feature qw(switch); + +my $m = 1000; # max value for prime list +my @primes = buildPrimes($m); + +my ($first,$second,$count) = (0,1,0); +for $first (0..$#primes-1){ + #print "$first "; + my $diff = $primes[$second] - $primes[$first]; + last if $second == $#primes or $count==6; + #print "$primes[$first] $primes[$second] :: "; + + given($diff){ + when(6){ + print "$primes[$first] $primes[$second]\n"; + #print "ok\n"; + $first++; + $second++; + $count++; + } + when($diff<6){ + $second++; + } + default{ + $first++; + } + } +} + +sub buildPrimes{ # building prime list + my $m=shift; + my @prime = (1)x($m+1); + @prime[0,1]=(0)x2; + for (my $p=2; $p*$p <= $m; $p++){ + if($prime[$p]==1){ + for(my $i= $p*$p; $i<= $m; $i+=$p){ + $prime[$i]=0; + } + } + } + @prime = grep{ $prime[$_] } 2..$m; + return @prime; +} + +sub isPrime{ # check primality + my $n = shift; + my $nSq = sqrt $n; + for my $i (@primes){ + last if $i>$nSq; + return 0 unless $n % $i; + } + return 1; +} -- cgit