in reply to Easy way to list prime numbers 1 to 100

You might want to check the definition of a prime number. After running your code, @primes includes a lot of numbers that aren't prime (9, 15 and 21 for example). In fact you seem to be calculating all of the odd numbers rather than the prime numbers.

  • Comment on Re: Easy way to list prime numbers 1 to 100

Replies are listed 'Best First'.
Re: Answer: Easy way to list prime numbers 1 to 100
by blazar (Canon) on May 22, 2006 at 11:01 UTC
    In fact you seem to be calculating all of the odd numbers rather than the prime numbers.

    Indeed, and in a very clumsy way, including the deprecated use of a map in void context...

    Update: at the moment of this update this node has gained a reputation of -4. So far so fine. However this should imply that at least four persons did disagree with my claim. I must deduce that those persons think that

    @prime = (1,2); map { push(@prime,$_) if (($_ % 2) != 0) } (2 .. 100);
    is a very nice, clean and elegant way to obtain the list of "primes" (in l.frankline's arithmetic) as opposed to, say,
    my @prime=(1,2,grep $_%2, 2..100);

    PS: from perldoc perlstyle:

    Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead.
      including the deprecated use of a map in void context

      Is map in a void context deprecated?

      I thought that the main concern with using map in a void context was the inefficiency of building a results list that is then discarded--but that was corrected in 5.8.1 (from the delta):

      map in void context is no longer expensive. map is now context aware, and will not construct a list if called in void context.

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Whilst I agree that deprecated is too strong a word and that it is no longer wasteful to use it in this way, it does seem semantically odd to use map in a void context, which I think has always been one of the major objections to doing this, something like:

        do { push(@prime,$_) if ($_ % 2) } for (2 .. 100);
        is probably closer to being clear (for me at any rate.)

        /J\