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.

In reply to Re: Spaces between outputs. by Laurent_R
in thread Spaces between outputs. by CPTQuesoXI

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.