# For loop that list all primes between 1 and 100

Posted 1 month ago
644 Views
|
9 Replies
|
1 Total Likes
|
 I have written a For loop that prints the first 100 prime numbers. But how would I modify it so that it prints all prime numbers between 1 and 100? I am very new to Mathematica so I am sorry if this is considered too basic. For[i = 1, i < 101, i++, Print[Prime[i]]; If[i > 100, Break]] Answer
9 Replies
Sort By:
Posted 1 month ago
 One way is: Select[Table[Prime[i], {i, 100}], # < 100 &] Answer
Posted 1 month ago
 Select[Range, PrimeQ[#] &] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, \ 59, 61, 67, 71, 73, 79, 83, 89, 97} Answer
Posted 1 month ago
 Or even Select[Range, PrimeQ] Answer
Posted 1 month ago
 Hello,I would use: Table[Prime[k], {k, 1, PrimePi}] Answer
Posted 1 month ago
 Here is one more: NextPrime[1, Range[PrimePi]] Answer
Posted 1 month ago
 In:= AbsoluteTiming[Length @ Select[Range[10^6], PrimeQ]] Out= {0.291042, 78498} In:= AbsoluteTiming[Length @ Table[Prime[k], {k, 1, PrimePi[10^6]}]] Out= {0.0311693, 78498} In:= AbsoluteTiming[Length @ Range[PrimePi[10^6]]] Out= {0.0000789, 78498} Answer
Posted 1 month ago
 The last one AbsoluteTiming[Length @ Range[PrimePi[10^6]]] does not give a list of the primes <= 10^6, just a list of 1 to PrimePi[10^6]] Answer
Posted 1 month ago
 In:= AbsoluteTiming[Length@ (l1 = Select[Range[10^6], PrimeQ])] Out= {0.307672, 78498} In:= AbsoluteTiming[ Length@ (l2 = Table[Prime[k], {k, 1, PrimePi[10^6]}])] Out= {0.0268336, 78498} In:= AbsoluteTiming[Length@ (l3 = Range[PrimePi[10^6]])] Out= {0.00016, 78498} In:= l1 == l2 Out= True In:= l2 == l3 Out= False Answer
Posted 1 month ago
 In:= AbsoluteTiming[Length@ (l1 = Select[Range[10^6], PrimeQ])] Out= {0.307672, 78498} In:= AbsoluteTiming[ Length@ (l2 = Table[Prime[k], {k, 1, PrimePi[10^6]}])] Out= {0.0268336, 78498} In:= AbsoluteTiming[ Length@ (l3 = NextPrime[1, Range[PrimePi[10^6]]])] Out= {0.933467, 78498} In:= l1 == l2 Out= True In:= l2 == l3 Out= True Answer