Finding The number of Divisors in a given number?
-
21-12-2019 - |
Question
I have created a Perl program to calculate the amount of divisible numbers in numbers 3 to 10.
Example: the number 6 has 4 divisors 1, 2, 3 and 6.
This is how the program is suppose to work:
The program will calculated the number of divisors of 3 it will then print it to the report.txt file. Next, it will move on to calculate the number of divisors of 4 and print it to report.txt. The program will do this until it has calculated to the number 10 then it will close the program.
#!/usr/bin/perl
use warnings;
use strict;
my $num = 2; # The number that will be calculated
my $count = 1; # Counts the number of divisors
my $divisors; # The number of divisors
my $filename = 'report.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!"; # open file "report.txt"
for (my $i=2; $i <= 10; $i++) {
while( $num % $i == 0) { # Checks if the number has a remainder.
$num++; # Adds 1 to $num so it will calculate the next number.
$count++; # counts the number of divisible numbers.
$num /= $i; # $num = $num / $i.
}
$divisors = $count; # The number of divisors are equal to $count.
print $fh "$divisors\n"; # The output will be repeated..
}
close $fh # Closes the file "report.txt"
I think the problem is that the for-loop keeps repeating this code:
print $fh "$divisors\n";
The output is:
2
2
2
2
2
2
2
2
2
but, I'm not sure exactly what I am missing.
Solution
Give your variables meaningful names. This helps in both making your code self-documenting, but also in that it helps you recognize when you're using a variable incorrectly. The variable name $i
doesn't communicate anything, but $divisor
says that you are testing if that number is a divisor.
As for why your code is looping, can't say. Here is a reformatted version of your code that does function though:
#!/usr/bin/perl
use warnings;
use strict;
use autodie;
for my $num (2..10) {
my $divisor_count = 0;
for my $divisor (1..$num) {
$divisor_count++ if $num % $divisor == 0;
}
print "$num - $divisor_count\n"
}
Output:
2 - 2
3 - 2
4 - 3
5 - 2
6 - 4
7 - 2
8 - 4
9 - 3
10 - 4