perl - Finding The number of Divisors in a given number? -


i have created perl program calculate amount of divisible numbers in numbers 3 10.

example: number 6 has 4 divisors 1, 2, 3 , 6.

this how program suppose work:

the program calculated number of divisors of 3 print report.txt file. next, move on calculate number of divisors of 4 , print report.txt. program until has calculated number 10 close program.

#!/usr/bin/perl use warnings; use strict;  $num = 2; # number calculated $count = 1; # counts number of divisors $divisors; # number of divisors  $filename = 'report.txt';  open(my $fh, '>', $filename) or die "could not open file '$filename' $!"; # open file "report.txt"  (my $i=2; $i <= 10; $i++) {            while( $num % $i == 0) { # checks if number has remainder.             $num++; # adds 1 $num calculate next number.             $count++; # counts number of divisible numbers.             $num /= $i; # $num = $num / $i.          }      $divisors = $count; # number of divisors equal $count.     print $fh "$divisors\n"; # output repeated.. }  close $fh # closes file "report.txt" 

i think problem for-loop keeps repeating code:

print $fh "$divisors\n"; 

the output is:

2 2 2 2 2 2 2 2 2 

but, i'm not sure missing.

give variables meaningful names. helps in both making code self-documenting, in helps recognize when you're using variable incorrectly. variable name $i doesn't communicate anything, $divisor says testing if number divisor.

as why code looping, can't say. here reformatted version of code function though:

#!/usr/bin/perl use warnings; use strict; use autodie;  $num (2..10) {     $divisor_count = 0;     $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 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -