2
$\begingroup$

I want to create a simple function that prints all prime numbers from 1 to x. I have the following code, which doesn't cause any errors from the kernel but it doesn't return anything:

allprimes[x_] = For[i=0, i<=x, i++, If[PrimeQ[i], Print[i]]]

What have I done wrong?

$\endgroup$
  • $\begingroup$ Try allprimes[x_] := For[i=0, i<=x, i++, If[PrimeQ[i], Print[i]]]; allprimes[7] $\endgroup$ – Bill Feb 8 at 3:13
  • $\begingroup$ Yep: an issue with Set (=) vs SetDelayed (:=). See the documentation. $\endgroup$ – march Feb 8 at 18:15
3
$\begingroup$
Clear[allprimes]

allprimes[x_] = For[i = 0, i <= x, i++, If[PrimeQ[i], Print[i]]]

Look at the stored definition of allprimes

?allprimes

enter image description here

Since you use Set the RHS evaluated immediately and was equal to Null. Use SetDelayed

Clear[allprimes]

allprimes[x_] := For[i = 0, i <= x, i++, If[PrimeQ[i], Print[i]]]

The stored definition is then

?allprimes

enter image description here

allprimes[5]

(* 2

3

5 *)

However, a more flexible approach is

Clear[allprimes]

allprimes[x_] := Select[Range[0, x], PrimeQ]

allprimes[5]

(* {2, 3, 5} *)
$\endgroup$
  • $\begingroup$ Thanks so much. I didn't think about the consequences of set vs set-delayed. $\endgroup$ – Jaigus Feb 8 at 3:26
3
$\begingroup$

You can use the functions Prime, PrimePi and Range:

ClearAll[primesLessThanOrEqualTo]
primesLessThanOrEqualTo[x_] := Prime[Range[PrimePi[x]]]
primesLessThanOrEqualTo[20]

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

A fancier way to define the same function as a pure function (composition of the three functions):

ClearAll[primesLessThanOrEqualTo2]
primesLessThanOrEqualTo2 = Prime@*Range@*PrimePi
primesLessThanOrEqualTo2[20]

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

You can also use a combination of NextPrime and NestWhileList as follows:

ClearAll[primesLessThanOrEqualTo3]
primesLessThanOrEqualTo3[x_] := Most@NestWhileList[NextPrime, 2, # <= x &]
primesLessThanOrEqualTo3[20]

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

Note: primesLessThanOrEqualTo and primesLessThanOrEqualTo2 are much faster than primesLessThanOrEqualTo3.

$\endgroup$

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