Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Spaces between outputs.

by Laurent_R (Canon)
on Mar 01, 2018 at 17:24 UTC ( [id://1210170]=note: print w/replies, xml ) Need Help??


in reply to Spaces between outputs.

Hi CPTQuesoXI,

you've been given perfectly good answers to your question and I won't comment further on that.

Your code works fine, but I would suggest an alternate (more efficient) algorithm for you to consider:

#! /usr/bin/perl use warnings; use strict; my $max = shift; my @primes = (2); my $i = 3; while ($i <= $max) { my $sqrt = sqrt $i; for my $num (@primes) { last if ($i % $num == 0); push @primes, $i and last if $num > $sqrt; } $i += 2; } print "1, @primes";
The two important differences are that this program only considers odd values for $i (since an even number won't be prime, except 2, no need to check even numbers), thereby reducing by half the number of values to test, and, more importantly, that it stores the primes found thus far in an array, so that, for each $i, it considers only primes found thus far (and smaller than the square root of $i) as possible divisors.

This is much more efficient for large input values.

When running your program for primes smaller than 1,000,000 on my computer, I get the following timings:

real 0m37.682s user 0m37.296s sys 0m0.015s
Running the program I suggested above for primes smaller than 1,000,000 on the same computer gives the following timings:
real 0m4.035s user 0m3.531s sys 0m0.062s
So this program is almost ten times faster in this case (primes below one million). This program is about 4.5 times faster when looking for for primes smaller than 100,000. And the difference between the two implementations would be even more significant when looking for primes below a limit larger than one million.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1210170]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-20 01:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found