1
$\begingroup$

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[15] (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?

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

Here's another way to write your function:

f[x_] := Total[Boole[PrimeQ[Range[0, x]]]];
{f[6], f[12], f[100]}
{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.

$\endgroup$
1
$\begingroup$

This works:

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

f[15]

(* 6 *)

Check:

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

(*

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

*)

Of course PrimePi solves the problem directly:

PrimePi[15]

(* 6 *)

$\endgroup$
1
$\begingroup$

Using recursion

Clear[f]

f[1] = 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 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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