One thing you should play with is 'memoization' and recursion. For those not familiar with the term, it is the caching of function results using the arguments as a key. In Perl, it's as simple as using the Memoize module. Not sure about the other languages' implementations.
Now, when calculating the factorial in a loop, memoization may not save you much. But in a recursive implementation, memoization is a tremendous win.
Something for you to have in your back pocket.
As for your Perl, it is very good - clear and very concise. One improvement for space and copy time considerations:
my @nums_to_multiply = (1..$x);
for(@nums_to_multiply){
$n *= $_;
}
can be replaced with
for(1..$x) {
$n *= $_;
}
That will save you the memory and the time to copy that series into the array.
Also, by adding use strict; at the top of your Perl code, you will get some errors about undefined vars. Just add mys in the appropriate places and you'll be fine. Always include use strict; in addition to use warnings;. It will catch unintended overlapping global usage of variables, which is a bear to debug, especially as the code gets longer. Again, excellent article.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
One thing you should play with is 'memoization' and recursion. For those not familiar with the term, it is the caching of function results using the arguments as a key. In Perl, it's as simple as using the Memoize module. Not sure about the other languages' implementations.
Now, when calculating the factorial in a loop, memoization may not save you much. But in a recursive implementation, memoization is a tremendous win.
Something for you to have in your back pocket.
As for your Perl, it is very good - clear and very concise. One improvement for space and copy time considerations:
can be replaced with
That will save you the memory and the time to copy that series into the array.
A second suggestion:
can be replaced with
No need in recalculating the same number over and over in the loop.
Excellent article.
Also, by adding
use strict;
at the top of your Perl code, you will get some errors about undefined vars. Just addmy
s in the appropriate places and you'll be fine. Always includeuse strict;
in addition touse warnings;
. It will catch unintended overlapping global usage of variables, which is a bear to debug, especially as the code gets longer. Again, excellent article.