Message Boards Message Boards

1
|
4721 Views
|
9 Replies
|
1 Total Likes
View groups...
Share
Share this post:

For loop that list all primes between 1 and 100

Posted 2 years ago

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]]
POSTED BY: Albin Nilsson
9 Replies
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
POSTED BY: Frank Kampas
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
POSTED BY: Frank Kampas
Posted 2 years 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]]

POSTED BY: Rohit Namjoshi
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 BY: Frank Kampas

Here is one more:

NextPrime[1, Range[PrimePi[100]]]
POSTED BY: Henrik Schachner
Posted 2 years ago

Hello,

I would use:

Table[Prime[k], {k, 1, PrimePi[100]}]
POSTED BY: Wiel Aerts
Posted 2 years ago

Or even

Select[Range[100], PrimeQ]
POSTED BY: Rohit Namjoshi
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 BY: Frank Kampas

One way is:

Select[Table[Prime[i], {i, 100}], # < 100 &]
POSTED BY: Mariusz Iwaniuk
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract