Task 1: Trailing Zeroes
You are given a positive integer $N (N >= 1). Write a script to calculate the total number of trailing zeroes in $N!.
Example Output
Input: $N = 10
Output: 2
Input: $N = 7
Output: 1
Input: $N = 4
Output: 0
Logic
The number of trailing zeroes in $N! is given by Legendre's formula by counting the total multiplicity of prime factor 5 in the product: floor(N/5) + floor(N/25) + floor(N/125) + .... We compute this sum iteratively with a while loop.
Perl Solution
ch-1.pl
sub trailing_zeros ($n) {
return 0 if $n <= 0;
my $count = 0;
my $divisor = 5;
while ( $n >= $divisor ) {
$count += int( $n / $divisor );
$divisor *= 5;
}
return $count;
}
Python Solution
ch-1.py
def trailing_zeros(n: int) -> int:
"""Calculate the number of trailing zeroes in n! by counting factors of 5."""
if n <= 0:
return 0
count = 0
divisor = 5
while n >= divisor:
count += n // divisor
divisor *= 5
return count
Task 2: Lines Range
You are given a text file name $file and range $A - $B where $A <= $B. Write a script to display lines in range $A and $B in the given file.
Example Output
Input: $file = 'input.txt', $A = 4, $B = 12
Output:
L4
L5
L6
L7
L8
L9
L10
L11
L12
Logic
Open the file, read all lines, and slice from 0-based index $A - 1 to $B - 1 inclusive, ensuring bounds checks so that requests outside the line count are handled gracefully.
Perl Solution
ch-2.pl
sub get_lines_range ( $file_name, $a, $b ) {
return [] if $a < 1 || $b < $a;
open my $fh, '<', $file_name or die "Could not open '$file_name': $!";
my @lines = <$fh>;
close $fh;
chomp @lines;
my $start_idx = $a - 1;
my $end_idx = $b - 1;
$end_idx = $#lines if $end_idx > $#lines;
return [] if $start_idx > $#lines;
my @result = @lines[ $start_idx .. $end_idx ];
return \@result;
}
Python Solution
ch-2.py
def get_lines_range(file_name: str | Path, a: int, b: int) -> list[str]:
"""Return lines from file within 1-based range [a, b] inclusive without trailing newlines."""
if a < 1 or b < a:
return []
with open(file_name, "r", encoding="utf-8") as f:
lines = f.readlines()
start_idx = max(0, a - 1)
end_idx = min(len(lines), b)
return [line.rstrip("\r\n") for line in lines[start_idx:end_idx]]