Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
I thought about this one also. But your implementation can be improved still. Let's look at 6!:

2 * 3 * 4 * 5 * 6 = | | | | | +-------+ | +---------------+ 4 * 12 * 15 = | | +---------+ 12 * 60 = 120
There are a couple of changes. First, there is no need to multiply by 1. The answer is not going to change :-). Second, you are correct in saying that it's best to multiply the smallest number by the largest first. So, in this case, the left over "4" from the first step should be the first number in the second step. These are implemented in fact8(). If you run it, you'll see that it run's just abit faster.

sub fact8{ #divide and conquer without recursion my @N = (2 .. shift); my @M; my $tmp; while ($#N){ while(@N){ $tmp = pop(@N); if (($_ = shift(@N))){push(@M,Math::BigInt->new($tmp)->bmul($_)) +} else {unshift(@M,$tmp)} } while(@M){ $tmp = pop(@M); if (($_ = shift(@M))){push(@N,Math::BigInt->new($tmp)->bmul($_)) +} else {unshift(@N,$tmp)} } } return @N; } perl fact.pl 5000 Method 8 (new func): 28 wallclock secs (28.65 usr + 0.00 sys = 28.65 +CPU) Method 7 (your func): 30 wallclock secs (29.06 usr + 0.00 sys = 29.06 + CPU)

In reply to Re: Re: Factorial algorithm execution time by gri6507
in thread Factorial algorithm execution time by gri6507

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-25 15:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found