# What is wrong with my procedural function to find all prime $\leq x$? [closed]

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?

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

Clear[allprimes]

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


Look at the stored definition of allprimes

?allprimes 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 allprimes

(* 2

3

5 *)


However, a more flexible approach is

Clear[allprimes]

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

allprimes

(* {2, 3, 5} *)

• Thanks so much. I didn't think about the consequences of set vs set-delayed. – Jaigus Feb 8 at 3:26

You can use the functions Prime, PrimePi and Range:

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


{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


{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


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

Note: primesLessThanOrEqualTo and primesLessThanOrEqualTo2 are much faster than primesLessThanOrEqualTo3.