The weekly challenge 254 - Task 1: Three Power
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-254/#TASK1 3 # 4 # Task 1: Three Power 5 # =================== 6 # 7 # You are given a positive integer, $n. 8 # 9 # Write a script to return true if the given integer is a power of three 10 # otherwise return false. 11 # 12 ## Example 1 13 ## 14 ## Input: $n = 27 15 ## Output: true 16 ## 17 ## 27 = 3 ^ 3 18 # 19 ## Example 2 20 ## 21 ## Input: $n = 0 22 ## Output: true 23 ## 24 ## 0 = 0 ^ 3 25 # 26 ## Example 3 27 ## 28 ## Input: $n = 6 29 ## Output: false 30 # 31 ############################################################ 32 ## 33 ## discussion 34 ## 35 ############################################################ 36 # 37 # Starting with $i at 0, count up to $n. If $i**3 == $n we have 38 # a third power, so return true. If $i**3 > $n we don't have a 39 # third power, so return false. 40 # 41 use strict; 42 use warnings; 43 44 three_power(27); 45 three_power(0); 46 three_power(6); 47 48 sub three_power { 49 my $n = shift; 50 print "Input: $n\n"; 51 foreach my $i (0..$n) { 52 last if $i**3 > $n; 53 if($i**3 == $n) { 54 print "Output: true\n"; 55 return; 56 } 57 } 58 print "Output: false\n"; 59 }