The weekly challenge 368 - Task 2: Big and Little Omega
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-368/#TASK2 3 # 4 # Task 2: Big and Little Omega 5 # ============================ 6 # 7 # You are given a positive integer $number and a mode flag $mode. If the mode 8 # flag is zero, calculate little omega (the count of all distinct prime factors 9 # of that number). If it is one, calculate big omega (the count of all prime 10 # factors including duplicates). 11 # 12 ## Example 1 13 ## 14 ## Input: $number = 100061 15 ## $mode = 0 16 ## Output: 3 17 ## 18 ## Prime factors are 13, 43, 179. Count is 3. 19 # 20 ## Example 2 21 ## 22 ## Input: $number = 971088 23 ## $mode = 0 24 ## Output: 3 25 ## 26 ## Prime factors are 2, 2, 2, 2, 3, 20231. Count of distinct numbers is 3. 27 # 28 ## Example 3 29 ## 30 ## Input: $number = 63640 31 ## $mode = 1 32 ## Output: 6 33 ## 34 ## Prime factors are 2, 2, 2, 5, 37, 43. Count including duplicates is 6. 35 # 36 ## Example 4 37 ## 38 ## Input: $number = 988841 39 ## $mode = 1 40 ## Output: 2 41 # 42 ## Example 5 43 ## 44 ## Input: $number = 211529 45 ## $mode = 0 46 ## Output: 2 47 # 48 ############################################################ 49 ## 50 ## discussion 51 ## 52 ############################################################ 53 # 54 # First, we create the list of prime factors. Then, dependent on 55 # $mode, we either keep it as is or filter it through List::Util's 56 # uniq() to get the list of distinct prime factors. In the end, we 57 # just need to get the number of elements of the resulting array. 58 59 use v5.36; 60 use List::Util qw(uniq); 61 62 big_and_little_omega(100061,0); 63 big_and_little_omega(971088,0); 64 big_and_little_omega(63640,1); 65 big_and_little_omega(988841,1); 66 big_and_little_omega(211529,0); 67 68 sub big_and_little_omega($number, $mode) { 69 say "Input: $number, $mode"; 70 my @factors = prime_factors($number); 71 @factors = uniq(@factors) unless $mode; 72 say "Output: " . scalar(@factors); 73 } 74 75 sub prime_factors($number) { 76 my @result = (); 77 foreach my $i (2..$number-1) { 78 if($number % $i == 0) { 79 push @result, $i; 80 push @result, prime_factors($number / $i); 81 return @result; 82 } 83 } 84 push @result, $number; 85 return @result; 86 } 87