Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I want to know how can I print out a list of prime numbers.

Should I use For, Do, If, maybe Mod, but If I can - no prime.

How should I approach this problem ?

share|improve this question
    
Try here for some algorithms. You can try asking us for help if you find problems implementing one of them. –  Timothy Wofford Oct 12 '13 at 13:17
    
possible duplicate of How can I simulate this animation of checking for prime numbers? –  Artes Oct 12 '13 at 16:07
add comment

closed as off-topic by Yves Klett, Artes, Pinguin Dirk, Sjoerd C. de Vries, Mr.Wizard Oct 12 '13 at 22:03

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Yves Klett, Sjoerd C. de Vries, Mr.Wizard
If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

Here is a fast implementation which translated from Matlab's primes function, And is slightly faster than that one。

primes[n_ /; n >= 2 && IntegerQ[n]] :=
  Module[{p = Range[1, n, 2]},
   p〚1〛 = 2;
   Do[ If[ p〚(k + 1)/2〛 != 0, p〚(k^2 + 1)/2 ;; ;; k〛 = 0], {k, 3, n^.5, 2}];
   SparseArray[p]["NonzeroValues"]
 ];

primes[10^7] // Length // AbsoluteTiming

{0.358020, 664579}

Prime@Range@PrimePi[10^7] // Length // AbsoluteTiming

{2.956169, 664579}

If you woud like to use For:

Module[{n = 10^2, flag, i, j},
 flag = ConstantArray[1, n];
 For[i = 2, i*i <= n, i++,
  If[flag[[i]] == 1,
    For[j = i*i, j <= n, flag[[j]] = 0; j += i]
    ];
  ];
 Rest@Pick[Range[n], flag, 1]
 ]

{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}

share|improve this answer
    
i do not understand matlab(?). i think this form solution. For[i = 1, If[, i, i = 0]; i ≤ 100, i++, Print[i]] –  hooha Oct 12 '13 at 13:56
add comment

Unless I'm missing some subtlety or misunderstanding the original question, what's wrong with the following?

    Prime[Range[20]]

{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}

share|improve this answer
    
I'd hazard a guess that "but If I can - no prime" means the OP doesn't want to use Prime - but hard to know for sure ... –  cormullion Oct 12 '13 at 15:21
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.