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]]
Select[Range[Sqrt[1000]], PrimeQ]– march Oct 13 '16 at 17:49Forloop:For[start, test, incr, body]. You need four inputs. You only have two specified. – march Oct 13 '16 at 17:50Prime /@ Range@PrimePi[Sqrt[1000]]. – march Oct 13 '16 at 17:53