# Prime number counting function

As part of an assignment for a calculus class, I have to write code for the prime number counting function $p(n)$, I have no problem creating the function itself, but for I want it as a function, rather than having to set a value for n each time individually, I would like to just be able to put f[(some value)] and have it return p(some value). However, when I write:

f[x_] = Total[Table[If[PrimeQ[n] == True, 1, 0], {n, 1, x, 1}]]


and subsequently follow with f (an example value), it gives me the following error:

Table: iterator {n,1,x,1} does not have appropriate bounds

Is it just not possible to have the variable be within the bounds?

• You need to use f[x_] := instead of f[x_] = – Jason B. Sep 6 '18 at 22:23
• – Jason B. Sep 6 '18 at 22:24
• Also you can take a look at PrimePi – roman465 Sep 7 '18 at 0:19

## 3 Answers

Here's another way to write your function:

f[x_] := Total[Boole[PrimeQ[Range[0, x]]]];
{f, f, f}
{3, 5, 25}


Range generates all the numbers between 1 and x, and PrimeQ gives True or False for each one. Boole changes the True and False into 1 and 0, and then Total adds up all the 1's.

This works:

f[x_Integer] := Total[Table[If[PrimeQ[n] == True, 1, 0], {n, 1, x}]];

f


(* 6 *)

Check:

Table[Prime[j], {j, 6}]


(*

{2, 3, 5, 7, 11, 13}

*)

Of course PrimePi solves the problem directly:

PrimePi


(* 6 *)

Using recursion

Clear[f]

f = 0;

f[x_Integer?Positive] := f[x] = f[x - 1] + Boole[PrimeQ[x]]

f /@ {6, 12, 100}

(* {3, 5, 25} *)

% == (PrimePi /@ {6, 12, 100})

(* True *)