1
$\begingroup$

I would like to write a function that outputs the built in function PrimePi, which gives the number of primes π(x) less than or equal to x. So far, I have:

enter[n_] := Count[[2, n], Prime] 

Any suggestions?

$\endgroup$
4
  • $\begingroup$ Edits to my code: myPrime = {}; en[n_] := For[i = 1, i < n, i ++, AppendTo[myPrime, Prime[i]];] Print[Length[myPrime]] $\endgroup$
    – ablam
    May 30, 2019 at 20:30
  • $\begingroup$ Your code contains the three markings of a beginner: For, AppendTo, and Print. More proper Mathematica code would be something like enter[n_Integer?Positive] := Range[n] // PrimeQ // Boole // Total. Please have a look at this tutorial and the most common pitfalls awaiting new users. $\endgroup$
    – Roman
    May 31, 2019 at 8:49
  • $\begingroup$ If you want to do this without using PrimeQ you could start by implementing the Sieve of Eratosthenes and then count the number of integers left over. $\endgroup$
    – Roman
    May 31, 2019 at 9:15
  • $\begingroup$ It looks like you are just guessing at the syntax instead of looking it up in the documentation. There is nothing wrong with trying to guess, but please do not stop there. Before you ask a question, look it up in the documentation. [2,n] is invalid syntax, the second argument of Count must be a pattern, etc. Go through these, look up Count in the docs, and ask about the specific problem where you got stuck (e.g. not sure how to write a correct pattern). $\endgroup$
    – Szabolcs
    May 31, 2019 at 13:06

1 Answer 1

3
$\begingroup$

I think the simplest working variation of your code is

enter[n_] := Count[Range[2, n], _?PrimeQ]

The function Count takes a pattern (look it up in the help). In this case, I'm matching anything that PrimeQ recognises as a prime.

$\endgroup$
1
  • $\begingroup$ That works. I've also got another code I've just written that avoiding Prime Q. Even though I use Prime, I'm trying to avoid the built in functions as much as possible. $\endgroup$
    – ablam
    May 30, 2019 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.