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

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

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]]

Let’s block ads! (Why?)

Recent Questions – Mathematica Stack Exchange