RabbitFarm

2020-08-09

n! has how many trailing zeroes?

Perl Weekly Challenge 072 asks 

You are given a positive integer $N (<= 10). Write a script to print number of trailing zeroes in $N!.

Note that the number of zeroes is equivalent to the number of factors of 10 in n!. For example, 4! = 4 * 3 * 2 * 1 which has none. 6! = 6 * 5 * 4 * 3 * 2 * 1 = 6 * 4 * 3 *1 * (5 * 2) has one. 10! = 10 * 9 * 8 * 7 * 6 * 4 * 3 * 1 * (5 * 2) has two.

In this case, for n <= 10, we can can these cases directly.

sub count_10s{
   my($n) = @_;
   return 2 if $n == 10;
   return 1 if $n >=5 && $n < 10;
   return 0 if $n < 5;
}
 

If we wanted to solve this for the general case we would have to follow an algorithm that would look like this (pseudo code)

Function count 10s   

    Pass In: n, a whole number   

    Doing: For each term of n! = 1 * 2 * 3 * ... * n perform a prime factorization.
                Save all prime factors for all terms to an array. Count each pair of
               (2,5). This is the number of factors of 10 in n!

    Pass Out: the number of factors of 10 in n! 

Endfunction 

posted at: 18:46 by: Adam Russell | path: /perl | permanent link to this entry

Using -s with Perl One Liners

For Perl Weekly Challenge 072 we are asked the following:

You are given a text file name $file and range $A -  $B where $A <= $B. Write a script to display lines range $A and $B in the given file.

I was a bit surprised to realize how this could be done with a one liner. In the example below input.txt is a plain text file which has 100 lines that all look like LX for 1 <= X <= 100.

$ perl -s -n -e 'print if $. >= $A && $. <= $B' — -A=4 -B=12 < input.txt

L4
L5
L6
L7
L8
L9
L10
L11
L12

The use of the special variable $. to track input line numbers is a common Perl idiom. What was surprising to me was that I was unfamiliar with the -s command line option. This option allows you to set variables on the command line. Anything after the is interpreted to be a variable initialized to the given value. You can see that in the example above where -A=4 and -B=12 creates variables $A and $B initialized to 4 and 12 respectively. 

If you do not set the variable to something then it is just initialized as true. For example:

$ perl -s -e 'print "$x\n";' — -x
1


posted at: 01:34 by: Adam Russell | path: /perl | permanent link to this entry