#!/usr/bin/perl -w use strict; my @primes = (2,3,5,7,11,13,17,19,23,29,31,37,41,
ID: 674157 • Letter: #
Question
#!/usr/bin/perl -w
use strict;
my @primes = (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);
sub listprimes {
my $n = shift;
my $i = 0;
my $answer = "";
while ($primes[$i]<=$n) {
$answer .= " $primes[$i]";
$i++;
}
return $answer;
}
sub random {
my($a,$b) = @_;
return int(rand($b-$a+1))+$a;
}
my $a = random(10,50);
my $f = listprimes($a);
print "$f ";
a) What does the code do? Give a detailed explanation.
b) Can you find any potential issue with this code?
c) Write a version of listprimes which uses a foreach loop and the push function.
Explanation / Answer
Solution :
a) The code executes and give the first 7 prime numbers as in output. List of prime numbers are to be inputed and the output gets is to be as 2, 3, 5, 7, 11, 13, 17. While list of primes numbers inputed, the shift is to be used which shift the position and give next number as in output.
b) No, their is no any potential issue with the given code. As it gives the proper output.
c) Version of listprimes which use for each loop can iterate over all the elements of an array and perform the same set of operations on each one of them. For example :
Version of listprimes which use push function can appends an element or an entire array to the end of an array variable. The syntax is push @array_to_append_to, @array_to_append or push @array, $elem1. For example :
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.