# Using a 'For' loop that outputs a list of positive integers starting from 1 whose squares are all less than 1000 and are prime

The code I have thus far to my question is here:

primes[m_] :=
(Clear[list, primes];
list = {};
For[k = 1,
k^2 < 1000,
k = k + 1,
If[PrimeQ[k^2 < 1000], AppendTo[list, k]]];
list);
primes[30]


I changed my code but it is still wrong. I will get this after some trial and error, hopefully.

• Select[Range[Sqrt[1000]], PrimeQ] – march Oct 13 '16 at 17:49
• Look at the syntax for a For loop: For[start, test, incr, body]. You need four inputs. You only have two specified. – march Oct 13 '16 at 17:50
• I love the Select command but this is a specific task I must do using loops (Even though Select command is essentially running a loop in the background), thanks for the advice, I will mess around with it! – Brandon Oct 13 '16 at 17:52
• – BlacKow Oct 13 '16 at 17:52
• Okay, I can help you with that. But also, for fun: Prime /@ Range@PrimePi[Sqrt[1000]]. – march Oct 13 '16 at 17:53

## 2 Answers

Direct fix for your For loop here, I would say:

Module[{list = {}, k},
For[k = 1, k < Sqrt[1000], k++, If[PrimeQ[k], AppendTo[list, k]]];
list
]


Using Sow and Reap rather than appending to a list (which is slow):

Last@Last@Reap@Module[{list = {}, k},
For[k = 1, k < Sqrt[1000], k++, If[PrimeQ[k], Sow[k]]];
list
]


Do is better than For:

Last@Last@Reap@Module[{list = {}, k},
Do[If[PrimeQ[k], Sow[k]], {k, Sqrt[1000]}];
list
]


The loop-like construction I would use to do this problem:

Last@Last@Reap@Module[{n = 1},
While[n < Sqrt[1000], If[PrimeQ[n++], Sow[n - 1]]]
]


Alternatively,

Select[Range[Sqrt[1000]], PrimeQ]


and, my favorite and probably the fastest,

Prime /@ Range@PrimePi[Sqrt[1000]]

• Great! although I am very unfamiliar with module, sow and reap. I appreciate your method! I'm still trying to go about it in my original way. I have edited my original code above but still doesn't work. – Brandon Oct 13 '16 at 18:35
• Module is a scoping construct. It basically does the thing you're trying to do with the Clear command by making local versions of the variables that don't leak out into the global variable space (i.e once the function is completed, list is left undefined). Sow and Reap are super-great. You should learn about them. – march Oct 13 '16 at 20:25
• Clear[list]; list = {}; For[ k = 1, k^2 < 1000, k = k + 1, If[PrimeQ[k], AppendTo[list, k]];]; list – Brandon Oct 13 '16 at 20:25
• @Brandon. Yep, that does it. (Also, see my previous comment: I forgot to ping you on it.) – march Oct 13 '16 at 20:26
• I was able to figure out my original code, its right above this comment. Thanks again for sticking through this with me! – Brandon Oct 13 '16 at 20:26

Just another way:

Prime[Range@PrimePi[Ceiling@Sqrt[1000]]]