# 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]] 
9 Replies
Sort By:
Posted 1 month ago
 One way is: Select[Table[Prime[i], {i, 100}], # < 100 &] 
Posted 1 month ago
 Select[Range[100], 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} 
Posted 1 month ago
 Or even Select[Range[100], PrimeQ] 
Posted 1 month ago
 Hello,I would use: Table[Prime[k], {k, 1, PrimePi[100]}] 
Posted 1 month ago
 Here is one more: NextPrime[1, Range[PrimePi[100]]] 
Posted 1 month ago
 In[4]:= AbsoluteTiming[Length @ Select[Range[10^6], PrimeQ]] Out[4]= {0.291042, 78498} In[5]:= AbsoluteTiming[Length @ Table[Prime[k], {k, 1, PrimePi[10^6]}]] Out[5]= {0.0311693, 78498} In[6]:= AbsoluteTiming[Length @ Range[PrimePi[10^6]]] Out[6]= {0.0000789, 78498} 
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]]
 In[1]:= AbsoluteTiming[Length@ (l1 = Select[Range[10^6], PrimeQ])] Out[1]= {0.307672, 78498} In[2]:= AbsoluteTiming[ Length@ (l2 = Table[Prime[k], {k, 1, PrimePi[10^6]}])] Out[2]= {0.0268336, 78498} In[3]:= AbsoluteTiming[Length@ (l3 = Range[PrimePi[10^6]])] Out[3]= {0.00016, 78498} In[4]:= l1 == l2 Out[4]= True In[5]:= l2 == l3 Out[5]= False 
 In[1]:= AbsoluteTiming[Length@ (l1 = Select[Range[10^6], PrimeQ])] Out[1]= {0.307672, 78498} In[2]:= AbsoluteTiming[ Length@ (l2 = Table[Prime[k], {k, 1, PrimePi[10^6]}])] Out[2]= {0.0268336, 78498} In[9]:= AbsoluteTiming[ Length@ (l3 = NextPrime[1, Range[PrimePi[10^6]]])] Out[9]= {0.933467, 78498} In[7]:= l1 == l2 Out[7]= True In[10]:= l2 == l3 Out[10]= True