1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-198/#TASK2 3 # 4 # You are given an integer $n > 0. 5 # 6 # Write a script to print the count of primes less than $n. 7 # 8 ## Example 1 9 ## 10 ## Input: $n = 10 11 ## Output: 4 as in there are 4 primes less than 10 are 2, 3, 5 ,7. 12 # 13 ## Example 2 14 ## 15 ## Input: $n = 15 16 ## Output: 6 17 # 18 ## Example 3 19 ## 20 ## Input: $n = 1 21 ## Output: 0 22 # 23 ## Example 4 24 ## 25 ## Input: $n = 25 26 ## Output: 9 27 # 28 ### This is a nice little task, so let's just simply count all the primes 29 ### up to $n-1 (since we want to count primes that are less than $n) 30 ### To do that, just check each of the integers up to $n whether it is 31 ### prime or not and increment a counter if it is 32 33 use strict; 34 use warnings; 35 use feature 'say'; 36 37 my @examples = (10, 15, 1, 25, 23, 30, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000); 38 39 foreach my $n (@examples) { 40 say "There are " . count_primes($n) . " primes < $n"; 41 } 42 43 # count all the primes < $n 44 sub count_primes { 45 my $n = shift; 46 my $count = 0; 47 # since we're only interested in primes less than $n, we only look for 48 # primes up to $n-1. Should $n be a prime itself, we don't count it 49 foreach my $i (1..$n-1) { 50 $count++ if is_prime($i); # increment $count in case we have a prime 51 } 52 return $count; 53 } 54 55 # helper function to check wether an integer is a prime 56 sub is_prime { 57 my $n = shift; 58 return 0 if $n < 2; # 1 isn't prime 59 foreach(2..sqrt($n)) { 60 # if any integer < sqrt($n) divides $n, we don't have a prime 61 return 0 unless $n % $_; 62 } 63 # since we didn't find any integer that divides $n, we have a prime 64 return 1; 65 }