List of primes under a million

56

12

This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

Delan Azabani

Posted 2012-05-26T07:24:50.913

Reputation: 693

12

It's not an exact duplicate, but it is essentially just primality testing, which is a component of a number of existing questions (e.g. http://codegolf.stackexchange.com/questions/113, http://codegolf.stackexchange.com/questions/5087 , http://codegolf.stackexchange.com/questions/1977 ). FWIW, one guideline which isn't followed enough (even by people who should know better) is to pre-propose a question in the meta sandbox http://meta.codegolf.stackexchange.com/questions/423 for criticism and discussion of how it can be improved before people start answering it.

– Peter Taylor – 2012-05-26T08:42:47.903

Ah, yes, I was worried about this question being too similar to the plethora of prime number-related questions already around. – Delan Azabani – 2012-05-26T08:44:30.843

1

A few years back I submitted an IOCCC entry that prints primes with only 68 characters in C -- unfortunately it stops well short of a million, but it might be of interest to some: http://computronium.org/ioccc.html

– Computronium – 2017-06-25T21:45:06.063

1@ɐɔıʇǝɥʇuʎs How about 1e6 :-D – Titus – 2018-03-03T02:09:05.810

In all those solutions that spell out "1000000", why not run to 999999 instead of 1000000, saves a byte. Everyone knows that 1000000 is not prime. – Glenn Randers-Pehrson – 2014-04-01T16:13:32.717

2@GlennRanders-Pehrson Because 10^6 is even shorter ;) – ɐɔıʇǝɥʇuʎs – 2014-05-14T05:20:28.473

Answers

33

Mathematica, 17 24

Just for comparison:

Prime@Range@78498

As noted in a comment I failed to provide one prime per line; correction:

Column@Prime@Range@78498

Mr.Wizard

Posted 2012-05-26T07:24:50.913

Reputation: 2 481

Would be nine bytes in mthmca, if that were to be released. – Michael Stern – 2016-05-28T10:53:35.297

That violates the condition of one prime per line of output. Prefixing with Print/@ and terminating with ; to prevent output of a long list of Nulls fixes that, at the cost of 8 extra characters. – celtschk – 2017-06-25T09:43:48.463

@celtschk I don't know if I missed or disregarded that five years ago. – Mr.Wizard – 2017-06-25T19:11:23.983

1Well, I definitely missed that it was from five years ago :-) – celtschk – 2017-06-25T19:36:04.480

4Prime~Array~78498 also 17 :) – chyanog – 2014-11-05T13:38:27.017

28

Python 3, 46 bytes

k=P=1
while k<1e6:P%k and print(k);P*=k*k;k+=1

By the time the loop reaches testing k, it has iteratively computed the squared-factorial P=(k-1)!^2. If k is prime, then it doesn't appear in the product 1 * 2 * ... * (k-1), so it's not a factor of P. But, if it's composite, all its prime factors are smaller and so in the product. The squaring is only actually needed to stop k=4 from falsely being called prime.

More strongly, it follows from Wilson's Theorem that when k is prime, P%k equals 1. Though we only need that it's nonzero here, it's useful in general that P%k is an indicator variable for whether k is prime.

xnor

Posted 2012-05-26T07:24:50.913

Reputation: 115 687

23

C, 61 chars

Almost exactly the same as this one (the question is almost exactly the same too).

n=2;main(m){n<1e6&&main(m<2?printf("%d\n",n),n:n%m?m-1:n++);}

ugoren

Posted 2012-05-26T07:24:50.913

Reputation: 16 527

This method is insane. I love it. – Todd Lehman – 2015-05-07T18:41:50.607

2I can get you to 57 bytes n=2;main(m){n<1e6&&main(m<2?printf("%d\n",n),n:m-++n%m);} – Albert Renshaw – 2016-10-01T06:10:19.513

Since n%m?m-1:n++ can be shortened to m-++n%m. Subtracting the conditional while nesting the increment in the conditional logic itself removes the need for the ternary operation! :D – Albert Renshaw – 2016-10-01T06:14:48.827

Looks nice, but unfortunately 13 is prime and 33 isn't. – ugoren – 2016-10-05T15:09:31.263

Got SEG-FAULT after printing 881 – manav m-n – 2014-07-21T07:32:54.953

7@Manav, perhaps you compiled without optimizations. It relies on a good optimizer, which will remove the recursion. – ugoren – 2014-07-21T10:50:03.493

4Yes adding -O3 to gcc solved the problem!! – manav m-n – 2014-07-21T11:23:47.983

22

MATLAB (16) (12)

Unfortunately, this outputs on a single line:

primes(1000000)

but that is solved by a simple matrix transpose:

primes(1000000)'

and I can cut out some characters by using exponential notation (as suggested in the comments):

primes(1e6)'

MBraedley

Posted 2012-05-26T07:24:50.913

Reputation: 329

@Axoren that does not include the ' at the end – Stan Strum – 2018-03-06T15:58:45.113

5Using 1e6 instead of 1000000 helps here too. – orion – 2014-05-14T18:53:38.257

@orion That would make it 11 characters – Axoren – 2014-10-31T07:18:01.513

20

Bash (37 chars)

seq 2 1e6|factor|sed 's/.*: //g;/ /d'

(60 chars)

seq 2 1000000|factor|sed -e 's/[0-9]*: //g' -e '/^.* .*$/ d'

on my computer (2.0 GHz cpu, 2 GB ram) takes 14 seconds.

saeedn

Posted 2012-05-26T07:24:50.913

Reputation: 1 241

This can be improved to: seq 2 1000000|factor|sed 's/[0-9]*: //g;/^.* .*$/ d' – Delan Azabani – 2012-05-26T09:13:07.987

yes you're right. I wrote my sed command clean, not golfed :P – saeedn – 2012-05-26T09:15:20.580

This can also further be improved to: seq 2 1000000|factor|sed 's/[0-9]*: //g;/ /d' – Delan Azabani – 2012-05-26T09:16:04.127

I was applying this improvement before I saw your comment ;) – saeedn – 2012-05-26T09:50:23.143

awk is faster and shorter in filtering this: seq 2 1000000|factor|awk '!$3&&$0=$2' – 37 characters. Or if you filter out the 1 case with awk, but the code's length is the same: seq 1000000|factor|awk 'NF==2&&$0=$2'. – manatwork – 2012-06-11T09:03:26.763

Yes, that awk script is about 25% faster :) – saeedn – 2012-06-11T12:23:48.707

3seq 1e6|factor|awk '$0=$2*!$3' is a bit shorter. – Dennis – 2014-04-02T23:23:00.087

1seq, factor and sed are external programs, this may as well be c p where c is a symlink to cat and p is a text file with primes up to a million... can you do it with shell builtins? – technosaurus – 2014-05-13T16:28:20.890

7@technosaurus seq and factor are in coreutils, so it's legitimate. sed is also pretty ubiquitous.

coreutils can be treated like a built-in. Bash without coreutils is like C++ without the STL. – None – 2014-05-13T16:32:40.287

16

J, 21 characters

1[\p:i.(_1 p:1000000)

which can be shortened to

1[\p:i.78498

if you know how many primes there are below 1000000.

Gareth

Posted 2012-05-26T07:24:50.913

Reputation: 11 678

2Using enfile items, ,., instead of 1[\ to save a character. Remove the unnecessary parenthesis, and use exponential notation: 1e6. – Omar – 2015-02-17T19:49:37.013

Came up with this: ,.i.&.(p:^:_1)1e6 Not shorter (after applying @Omar 's suggestions) but I found the use of under interesting. – kaoD – 2017-03-27T17:25:46.327

10

PowerShell, 47 44 bytes

Very slow, but the shortest I could come up with.

$p=2..1e6;$p|?{$n=$_;!($p-lt$_|?{!($n%$_)})}

PowerShell, 123 bytes

This is much faster; far from optimal, but a good compromise between efficiency and brevity.

 $p=2..1e6;$n=0
 while(1){$p=@($p[0..$n]|?{$_})+($p[($n+1)..($p.count-1)]|?{$_%$p[$n]});$n++;if($n-ge($p.count-1)){break}}
 $p

Rynant

Posted 2012-05-26T07:24:50.913

Reputation: 2 353

9

Ruby 34

require'prime';p Prime.take 78498

Hauleth

Posted 2012-05-26T07:24:50.913

Reputation: 1 472

8

APL, 15

p~,p∘.×p←1↓⍳1e6

My interpreter ran into memory problems, but it works in theory.

TwiNight

Posted 2012-05-26T07:24:50.913

Reputation: 4 187

How? Can you give a deskription? – Rasmus Damgaard Nielsen – 2015-08-31T20:39:04.997

You need a in front to make one number per line, and you don't need the ,. – Adám – 2015-09-03T08:18:31.460

@RasmusDamgaardNielsen are the first integers. 1↓ drops the first one. p← assigns to p. p∘.×p makes a multiplication table. p~ removes from p whatever is on the right. (, isn't needed, it ravels the table into a list.) – Adám – 2015-09-03T08:21:32.980

8

Haskell, 51

mapM print [n|n<-[2..10^6],all((>0).rem n)[2..n-1]]

pt2121

Posted 2012-05-26T07:24:50.913

Reputation: 309

You can replace 999999 with 10^6. And please update your byte count - 63 can't possibly be right. – user2845840 – 2015-07-29T22:21:24.720

@user2845840 ok thanks. good idea! – pt2121 – 2015-07-30T00:47:11.540

You can change mapM_ to mapM, return value won't be printed, and this is Code Golf. ;) – Wile E. Coyote – 2013-10-31T10:58:59.527

why are there extra spaces after print and in (> 0)? – proud haskeller – 2014-08-04T02:52:09.200

nice catch! thanks – pt2121 – 2014-08-04T03:00:00.617

8

Perl, 49 bytes

Regular expression kung fu :)

for(1..1E6){(1x$_)=~/^(11+?)\1+$/ or print"$_\n"}

Ungolfed version:

for(1 .. 1_000_000) { 
    (1x$_) =~ /^(11+?)\1+$/ or print "$_\n";
}

It hasn't even made 10% progress while I type this post!

Source for the regex: http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

Gowtham

Posted 2012-05-26T07:24:50.913

Reputation: 571

1Also, 1000000 can be written 1E6 – mob – 2015-05-07T21:02:07.350

Updated my answer. Thanks @mob – Gowtham – 2015-10-03T17:42:47.067

Always was a favorite regex of mine, but you need to remember that it fails spectacularly once you get to higher numbers - because of the fact that it's converting huge numbers into unary. This regex might not work for finding primes in the hundreds of thousands and beyond, depending on one's configuration of the language (and your machine.) – Codefun64 – 2015-10-03T18:10:31.587

2inspired me to write a perl6 version. also, 1000000 can be written 10**6 – pabo – 2014-08-04T22:17:03.320

8

Bash, 37

Will golf more, if I can...

Most of this is trying to parse factor's awkward output format.

seq 1e6|factor|grep -oP "(?<=: )\d+$"

Takes 5.7 or so seconds to complete on my machine.

(It just happened that my post was the first to go on the second page of answers, so nobody is going to see it...)

Old solution

This is longer and slower (takes 10 seconds).

seq 1e6|factor|egrep ':.\S+$'|grep -oE '\S+$'

user16402

Posted 2012-05-26T07:24:50.913

Reputation:

2Wow - I never came across factor before, but there it is right there in coreutils! – Digital Trauma – 2014-05-13T21:23:40.793

1Shave off one character: seq 1e6|factor|grep -oP "(?<=: )\d+$" with a perl-grep lookbehind – Digital Trauma – 2014-05-13T21:35:54.913

@DigitalTrauma how does that work – None – 2014-05-14T07:24:08.030

1-P enables perl-style regexes. (?<=: ) is a positive lookbehind for the string ": ". Basically this says that ": " must come before what matches \d+$, but is not actually part of the match, so the -o option just gives us one matching number after the colon, i.e. just gives numbers where there is only one factor, i.e. prime. – Digital Trauma – 2014-05-14T16:21:59.327

@DigitalTrauma added – None – 2014-05-14T16:34:52.973

8

Bash, 30 bytes

Since saeedn won't act on my suggestion – which is both shorter and faster than his approach – I thought I'd post my own answer:

seq 1e6|factor|awk '$0=$2*!$3'

How it works

seq 1e6

lists all positive integers up to 1,000,000.

factor

factors them one by one. For the first ten, the output is the following:

1:
2: 2
3: 3
4: 2 2
5: 5
6: 2 3
7: 7
8: 2 2 2
9: 3 3
10: 2 5

Finally,

awk '$0=$2*!$3'

changes the entire line ($0) to the product of the second field (the first prime factor) and the logical negation of the third field (1 if the is one prime factor or less, 0 otherwise).

This replaces lines corresponding to prime numbers with the number itself and all other lines with zeros. Since awk only prints truthy values, only prime number will get printed.

Dennis

Posted 2012-05-26T07:24:50.913

Reputation: 196 637

4awk '$0=$2*!$3' is awksome cool! – None – 2014-05-15T00:36:49.543

8

Ruby 50 41

require'mathn'
p (2..1e6).select &:prime?

Cristian Lupascu

Posted 2012-05-26T07:24:50.913

Reputation: 8 369

2

No need for .to_a, as Enumerable already includes select. You can also use the shorthand notation for Symbol#to_proc to shorten it further: p (2..1e6).select &:prime? (1 is not prime)

– Ventero – 2012-05-26T19:41:27.637

@Ventero thanks a lot! I didn't know about the Symbol#to_proc. I gotta pay more attention to the shortcuts Ruby offers. – Cristian Lupascu – 2012-05-26T19:53:34.353

Good use of some good ol' country boy mathn' – DoctorHeckle – 2016-04-27T20:22:15.013

2Shorter version require'prime';p Prime.take 78498. – Hauleth – 2013-11-25T10:46:31.150

@ŁukaszNiemier Great! I think that's so different that you can post it as a separate answer. – Cristian Lupascu – 2013-11-25T14:08:45.887

8

Python 3.x: 66 chars

for k in range(2,10**6):
 if all(k%f for f in range(2,k)):print(k)

More efficient solution: 87 chars

Based on the Sieve of Eratosthenes.

p=[];z=range(2,10**6)
while z:f=z[0];p+=[f];z=[k for k in z if k%f]
for k in p:print(k)

dan04

Posted 2012-05-26T07:24:50.913

Reputation: 6 319

1The first one erroneously prints 0 and 1. You can fix this by instead using range(2,10**6). Also, I think the if statement has to be on a separate line from the out for or you get an error. – xnor – 2014-05-13T20:52:14.397

@xnor: Fixed it. – dan04 – 2014-08-03T20:15:27.367

7

J (15 or 9)

I can't believe this beat Mathematica (even if it's just a single by 2 chars)

a#~1 p:a=:i.1e6

Or:

p:i.78498

ɐɔıʇǝɥʇuʎs

Posted 2012-05-26T07:24:50.913

Reputation: 4 449

1... The output format should be one number per line of output. That's why my answer begins with 1[\. – Gareth – 2014-05-15T08:05:38.630

7

Julia, 11

primes(10^6)

It looks like built ins are getting upvotes, plus I needed more words for longer answer.

gggg

Posted 2012-05-26T07:24:50.913

Reputation: 1 715

6

gs2, 5 bytes

Encoded in CP437:

∟)◄lT

1C 29 pushes a million, 11 6C is primes below, 54 is show lines.

Lynn

Posted 2012-05-26T07:24:50.913

Reputation: 55 648

5

GolfScript, 22/20 (20/19) bytes

n(6?,:|2>{(.p|%-.}do:n

At the cost of speed, the code can be made two bytes shorter:

n(6?,:|2>.{|%2>-}/n*

If the output format specified in the edited question is disregarded (which is what many of the existing answers do), two bytes can be saved in the fast version and one can be saved in the slow one:

n(6?,:|2>{(.p|%-.}do
n(6?,:|2>.{|%2>-}/`

This will print an additional LF after the primes for the fast version, and it will print the primes as an array for the slow one.

How it works

Both versions are implementations of the sieve of Eratosthenes.

The fast version does the following:

  1. Set A = [ 2 3 4 … 999,999 ] and | = [ 0 1 2 … 999,999 ].

  2. Set N = A[0] and print N.

  3. Collect every N-th element from | in C. These are the multiples of N.

  4. Set A = A - C.

  5. If A is non-empty, go back to 2.

n(6?   # Push "\n".pop() ** 6 = 1,000,000.
,:|    # Push | = [ 0 1 2 … 999,999 ].
,2>    # Push A = [ 2 3 4 … 999,999 ].
{      #
  (    # Unshift the first element (“N”) of “A”.
  .p   # Print “N”.
  |%   # Collect every N-th element from “A” into a new array, starting with the first.
  -    # Take the set difference of “A” and the array from above.
  .    # Duplicate the set difference.
}do    # If the set difference is non-empty, repeat.
:n     # Store the empty string in “n”, so no final LF will get printed.

The slow version works in a similar fashion, but instead of successively removing multiples of the minimum of “A” (which is always prime), it removes multiples of all positive integers below 1,000,000.

Competitiveness

In absence of any built-in mathematical functions to factorize or check for primality, all GolfScript solutions will either be very large or very inefficient.

While still far from being efficient, I think I have achieved a decent speed-to-size ratio. At the time of its submission, this approach seems to be the shortest of those that do not use any of the aforementioned built-ins. I say seems because I have no idea how some of the answers work...

I've benchmarked all four submitted GolfScript solutions: w0lf's (trial division), my other answer (Wilson's theorem) and the two of this answer. These were the results:

Bound     | Trial division     | Sieve (slow)       | Wilson's theorem | Sieve (fast)
----------+--------------------+--------------------+------------------+----------------
1,000     | 2.47 s             | 0.06 s             | 0.03 s           | 0.03 s
10,000    | 246.06 s (4.1 m)   | 1.49 s             | 0.38 s           | 0.14 s
20,000    | 1006.83 s (16.8 m) | 5.22 s             | 1.41 s           | 0.38 s
100,000   | ~ 7 h (estimated)  | 104.65 (1.7 m)     | 35.20 s          | 5.82 s
1,000,000 | ~ 29 d (estimated) | 111136.97s (3.1 h) | 3695.92 s (1 h)  | 418.24 s (7 m)

Dennis

Posted 2012-05-26T07:24:50.913

Reputation: 196 637

Is the "slow" sieve just a Sieve of Eratosthenes? – user8397947 – 2016-05-27T00:15:48.017

Both are. The slow version is just an awful implementation. – Dennis – 2016-05-27T00:17:54.947

5

NARS2000 APL, 7 characters

⍸0π⍳1e6

TheHive

Posted 2012-05-26T07:24:50.913

Reputation: 59

3Welcome to Programming Puzzles & Code Golf! – Dennis – 2015-09-26T14:29:10.070

4

GolfScript, 25 (24) bytes

!10 6?,2>{.(@*.)@%!},n*\;

If the output format specified in the edited question is disregarded, one byte can be saved:

!10 6?,2>{.(@*.)@%!},`\;

This will print the primes as an array (like many other solutions do) rather than one per line.

How it works

The general idea is to use Wilson's theorem, which states that n > 1 is prime if and only if

                                                      (n - 1)! = -1 (mod n)

!     # Push the logical NOT of the empty string (1). This is an accumulator.
10 6? # Push 10**6 = 1,000,000.
,2>   # Push [ 2 3 4 … 999,999 ].
{     # For each “N” in this array:
  .(  # Push “N - 1”.
  @   # Rotate the accumulator on top of the stack.
  *   # Multiply it with “N - 1”. The accumulator now hold “(N - 1)!”.
  .)  # Push “(N - 1)! + 1”
  @   # Rotate “N” on top of the stack.
  %!  # Push the logical NOT of “((N - 1)! + 1) % N”.
},    # Collect all “N” for which “((N - 1)! + 1) % N == 0” in an array.
n*    # Join that array by LF.
\;    # Discard the accumulator.

Benchmarks

Faster than trial division, but slower than the sieve of Eratosthenes. See my other answer.

Dennis

Posted 2012-05-26T07:24:50.913

Reputation: 196 637

4

CJam - 11

1e6,{mp},N*

1e6, - array of 0 ... 999999
{mp}, - select primes
N* - join with newlines

aditsu quit because SE is EVIL

Posted 2012-05-26T07:24:50.913

Reputation: 22 326

1Isn't CJam more recent than this question? – Peter Taylor – 2014-07-14T13:21:54.877

@PeterTaylor oh, yes it is – aditsu quit because SE is EVIL – 2014-07-14T14:23:43.470

4

Golfscript 26 25 24

Edit (saved one more char thanks to Peter Taylor):

10 6?,{:x,{)x\%!},,2=},`

Old code:

10 6?,{.,{)\.@%!},,2=*},`

This code has only theoretical value, as it is incredibly slow and inefficient. I think it could take hours to run.

If you wish to test it, try for example only the primes up to 100:

10 2?,{:x,{)x\%!},,2=},`

Cristian Lupascu

Posted 2012-05-26T07:24:50.913

Reputation: 8 369

You can save a character by replacing \; with *. (You can also get much faster for the current character count by finding the first divisor rather than all of them: `10 6?,2>{.),2>{1$%!}?=},`` – Peter Taylor – 2012-05-26T23:05:55.337

@PeterTaylor Thanks, using multiplication there is a very neat trick. – Cristian Lupascu – 2012-05-27T09:42:45.797

There's one more char saving with a variable: replace ., with :x, and \.@ with x\ (whitespace is because of escaping issues with MD in comments) and remove *. – Peter Taylor – 2014-04-01T15:10:35.747

@PeterTaylor good one, thanks! I've edited my code. – Cristian Lupascu – 2014-04-01T15:34:53.723

4

Java, 110 bytes

void x(){for(int i=1;i++<1e6;)System.out.print(new String(new char[i]).matches(".?|(..+?)\\1+")?"":(i+"\n"));}

Using unary division through regex as a primality test.

Addison Crump

Posted 2012-05-26T07:24:50.913

Reputation: 10 763

1

Nice approach. Never seen that prime-regex before. +1 from me. Although, using a nested for-loop for prime-checking is slightly shorter. :)

– Kevin Cruijssen – 2016-10-14T08:49:34.513

3

R, 45 43 characters

for(i in 2:1e6)if(sum(!i%%2:i)<2)cat(i," ")

For each number x from 2 to 1e6, simply output it if the number of x mod 2 to x that are equal to 0 is less than 2.

plannapus

Posted 2012-05-26T07:24:50.913

Reputation: 8 610

The first number produced by this code is 1, but 1 is not a prime. – Sven Hohenstein – 2013-11-17T18:32:17.353

@SvenHohenstein Thanks, corrected. – plannapus – 2013-11-20T07:51:35.807

3

Mathematica 25

Assuming you don't know the number of primes less than 10^6:

Prime@Range@PrimePi[10^6]

DavidC

Posted 2012-05-26T07:24:50.913

Reputation: 24 524

3

J, 16 chars

1]\(#~1&p:)i.1e6

Without the output format requirement, this can be reduced to 13 chars:

(#~1&p:)i.1e6

1]\ just takes the rank 1 array of primes, turns it into a rank 2 array, and puts each prime on its own row -- and so the interpreter's default output format turns the one line list into one prime per line.

(#~ f) y is basically filter, where f returns a boolean for each element in y. i.1e6 is the range of integers [0,1000000), and 1&p: is a boolean function that returns 1 for primes.

rationalis

Posted 2012-05-26T07:24:50.913

Reputation: 456

3

Bash (433643)

My (not so clever) attempt was to use factor to factor the product.

factor ${PRODUCT}

Unfortunately with large numbers the product is of course huge. It also took over 12 hours to run. I decided to post it though because I thought it was unique.

Here is the full code.

If it was primes under six it would be reasonable.

  factor 30

Oh well, I tried.

Kevin Cox

Posted 2012-05-26T07:24:50.913

Reputation: 451

+1 This answer is truly diabolical. Not quite precomputed result (it saves quite a bit of characters), and much much more terrible to compute :) It's quite possibly also an example that makes the optimized factor perform much worse than the basic trial division algorithm. – orion – 2014-05-15T06:59:40.323

3

C#, 70

Enumerable.Range(1,1e6).Where(n=>Enumerable.Range(2,n).All(x=>x%n!=0))

You're not going to see much here though for a LONG time...

It'sNotALie.

Posted 2012-05-26T07:24:50.913

Reputation: 209

There are several reasons why this is wrong. (1) You cannot implicitly convert from a double 1e6 to an int, but int is required by Range. (2) The inner Range must take at most n-2 terms, otherwise you will test n % n which is clearly 0. (3) You write x%n when you want n%x. Fixing these issues, something like this will work: Enumerable.Range(2,999999).Where(n=>Enumerable.Range(2,n-2).All(x=>n%x!=0)) However, this still does not output the numbers; the requirement was one per line. – Jeppe Stig Nielsen – 2019-05-29T22:39:18.343

3

NARS2000 APL - 9 characters

¯2π⍳2π1e6

Quite a boring answer.

Short explanation:

¯2 π  ⍝ generate the Nth prime for N
⍳     ⍝ in the range 1 to
2 π   ⍝ the number of primes less than or equal to
1e6   ⍝ a million

Oberon

Posted 2012-05-26T07:24:50.913

Reputation: 2 881

You need for the proper output (and btw, ¯2π⍳78498 is much simpler). – Adám – 2016-06-28T20:05:03.700

This is sinister black magic. – None – 2014-05-13T18:40:25.037

@professorfish I assume I should add an explanation? – Oberon – 2014-05-13T18:41:02.973

yessssssss (putting in extra sssss because of char limit_) – None – 2014-05-13T18:42:26.560

3

HPPPL, 90 89 chars

(HP Prime Programming Language), for the HP Prime color graphing calculator.

export p()begin local i;for i from 2 to 1e6 do if isprime(i)=1 then print(i) end;end;end;

Output to the terminal is quite slow on the Prime, so the program takes quite a while to run. Printing out all primes using the emulator takes about 88 seconds on my i5 2410M laptop.

As my google account is messed up, I have to start all over again with a new account... so be it. My photo and name are the same as before ;)

You can try out the program with the free HP Prime emulator available here:

http://www.hp-prime.de/en/category/13-emulator

M L

Posted 2012-05-26T07:24:50.913

Reputation: 2 865

3

F#, 100 94 bytes

let p n=
    let rec c i=i>n/2||(n%i<>0&&c(i+1))
    c 2
for n in 1..1000000 do if p n then printfn "%i" n

let p n={2..n-1}|>Seq.forall(fun x->n%x<>0)
{2..1000000}|>Seq.filter p|>Seq.iter(printfn "%i")

Smetad Anarkist

Posted 2012-05-26T07:24:50.913

Reputation: 363

3

C, 91 88 85 82 81 80 76 72 characters

main(i,j,b){for(;i++<1e6;b++&&printf("%d\n",i))for(j=2;j<i;)b=i%j++&&b;}

The algorithm is terribly inefficient, but since we're doing code-golf that shouldn't matter.

Gareth

Posted 2012-05-26T07:24:50.913

Reputation: 11 678

1you can shorten it easily: main(i,j,b){for(;i++<1e6;b++&&printf("%d\n",i))for(j=2;j<i;)b=i%j++&&b;} or some idea like this (since I actually didn't compile it) – Ali1S232 – 2012-05-27T11:34:41.173

How is i sure to be 0? I think that, if you provide any argument, it'll fail. Also, I think j will have some sort of type error. Not sure for b though. – Erik the Outgolfer – 2016-07-17T21:57:57.413

3

QBASIC, 75 bytes

FOR I=2 TO 1e6
    FOR J=2 TO I^.5
        IF I MOD J=0 THEN:GOTO X
    NEXT
    ?I
X:NEXT

I could have saved a character by going with FOR J = 2 TO I/2 but the run time was seriously slow. Runs at a much saner speed by only going to Sqrt I.

Kibbee

Posted 2012-05-26T07:24:50.913

Reputation: 919

2

PHP, 55 53 51 bytes

for($n=1;1e6>$i=$n++;$i||print"$n
")while($n%$i--);

Run with -nr or try it online. (TiO only runs to 10K; 1M would exceed the time limit.)

The outer loop runs $n from 1 to 1 million.
The inner loop is the primality test: loops $i down from $n-1 until $i is a divisor of $n.
If that divisor is 1, $n is a prime and will be printed in the post-condition of the outer loop.

Titus

Posted 2012-05-26T07:24:50.913

Reputation: 13 814

2

Javascript, 74 73 bytes

saved one byte thanks to Martin Ender

()=>{for(i=0;i<1e6;i++)!/^.?$|^(..+)\1+$/.test('1'.repeat(i))&&alert(i);}

Tests all numbers under 1 million against a regex. Regex Explanation

SuperStormer

Posted 2012-05-26T07:24:50.913

Reputation: 927

2

Jelly, 7 bytes

10*6ÆRY

Try it online!

10*6    # One million in scientific notation (10^6 = 1,000,000).
    ÆR  # List of primes less than one million.
      Y # Join the list with newlines.

MooseOnTheRocks

Posted 2012-05-26T07:24:50.913

Reputation: 191

1Welcome to PPCG! – Martin Ender – 2017-06-25T21:16:14.563

I improved the formatting and added in a Try It Online link. Also 5 bytes

– caird coinheringaahing – 2017-12-09T12:34:35.150

@cairdcoinheringaahing not sure if it was in the syntax at the time, but you could replace 10*6 with ȷ6 to save a byte. – Nick Kennedy – 2019-06-15T08:21:52.797

2

Octave, 12, 11

primes(1e6)

Write 1000000 as 1e6

MrD

Posted 2012-05-26T07:24:50.913

Reputation: 171

11e6 is even shorter ;) – jpjacobs – 2013-10-30T13:31:42.560

Editted in. Thanks for the info :) – MrD – 2013-10-30T21:17:50.000

2

Befunge-98, 119 characters

Because if it can be done, it can be done in Befunge! Probably not optimal. Works in 98 but not 93 because of the difference in how many bits a cell can store.

2.300p210pv>a,00g:.2+00>p"d"::**v
>00g1-10g`!|Prime Get> ^|p012!`\<
| %g01g00 <>10g1+10pv  v<
>00g:2+00#^        #<^#<@

MDS

Posted 2012-05-26T07:24:50.913

Reputation: 61

2

Python 2; 67 Bytes

n,p=3,[2]
while n<1e5:exec'print n;p+=[n]'*all(n%x for x in p);n+=2

Checks current number against all previous primes, and if not divisible by any of them, prints number and adds to list

The advantage of the while loop compared to other methods is that python will allow direct comparison against a number of the form "1e5", rather than having to use a long form or convert it to an int

Still takes a long time to run

Chromane

Posted 2012-05-26T07:24:50.913

Reputation: 161

2

FORTRAN 90, 80 bytes

DO I=2,1E2;D=1;DO J=2,I**.5;IF(MOD(I,J)==0)D=0;ENDDO;IF(D==1)PRINT*,I;ENDDO;END

This is the same as below, but in a newer and less rigorous version.


FORTRAN 77, 104 95 bytes

      DOI=2,1E6;D=1;DOJ=2,I**.5;IF(MOD(I,J).EQ.0)D=0;
      ENDDO;IF(D.EQ.1)PRINT*,I;ENDDO;END

Works with gfortran. Not sure if the DO I=... and DO J=... works without spaces in other compilers.

(Modification: program name supressed; I just learned that it's optional!)

rafa11111

Posted 2012-05-26T07:24:50.913

Reputation: 310

2

05AB1E, 6 bytes

6°ÅPε,

Try it online!

Explanation:

6°ÅPε,
6°       Push 1000000 to stack (10^6)
  ÅP     List of all primes < 1000000
    ε,   Print each element of the list

Geno Racklin Asher

Posted 2012-05-26T07:24:50.913

Reputation: 466

You can save a byte changing ε, to » (join by newlines; after which the result is implicitly output). – Kevin Cruijssen – 2018-11-09T14:47:08.483

2

Perl 6, 27 bytes

grep(&is-prime,^)>>.say

Try it online!

Filters all the primes from 0 to a million minus 1 and then prints.

Jo King

Posted 2012-05-26T07:24:50.913

Reputation: 38 234

2

PHP - 72 bytes

<?for($i=1;$i++^999999;print$d?~ı.$i:'')for($d=$j=2;$j<$i&&$d=$i%$j++;);

Hexdump:

0000000 3c 3f 66 6f 72 28 24 69 3d 31 3b 24 69 2b 2b 5e
0000010 39 39 39 39 39 39 3b 70 72 69 6e 74 24 64 3f 7e
0000020 f5 2e 24 69 3a 27 27 29 66 6f 72 28 24 64 3d 24
0000030 6a 3d 32 3b 24 6a 3c 24 69 26 26 24 64 3d 24 69
0000040 25 24 6a 2b 2b 3b 29 3b                        
0000048

Kinda slow, could be optimised (for 6 bytes) by division-checking until the square root of each number only, like so:

<?for($i=1;$i++^999999;print$d?~ı.$i:'')for($d=$j=2;$j<sqrt($i)&&$d=$i%$j++;);

Aurel Bílý

Posted 2012-05-26T07:24:50.913

Reputation: 1 083

2

Commodore 64 Basic, 55 characters

1F┌I=2TO10^6:F┌J=2TOI/2:IF(I/J=INT(I/I))G┌3
2N─:?I
3N─I

PETSCII substitutions: = SHIFT+O, = SHIFT+E

Incredibly slow: first, because the algorithm is extremely inefficient (it tries dividing by every value less than half the candidate number), second, because the Commodore 64 is slow, and third, because Commodore Basic does all its math in emulated floating-point on an 8-bit CPU.

Theoretical solution, 82 characters

1M=10^6:D╮S(M):F┌I=2TO1000:F┌J=I^2TOMST─I:S(J)=-1:N─:N─:F┌I=2TOM:IF(N┌S(I))T|:?I
2N─

= SHIFT+I, = SHIFT+O, = SHIFT+E, | = SHIFT+H

If this program could run on an actual Commodore 64, it would be much faster than the above. However, it can't: the sieve alone would take 5,000,007 bytes out of the 38,911 bytes a C64 has available for Basic programs. Note the use of -1 instead of 1 when denoting composite values in the array: C64 Basic doesn't have a true boolean negation; NOT performs a two's complement instead.

Mark

Posted 2012-05-26T07:24:50.913

Reputation: 2 099

I think that should be INT(I/J) not I/I. Btw. that´s 56 bytes; and 56 characters (the last line needs a RETURN as well so it gets recognized). 1F┌I=2TO10^6:F┌J=2TOI/2:IF(I/J!=INT(I/I))N─:?I and 2N─I is four characters shorter and six bytes smaller. Nice approach though. – Titus – 2018-03-03T12:31:32.510

Oh and for those that think that integer varibales would be faster: They´re not. Commodore Basic transforms integer values to float for calculations. – Titus – 2018-03-03T12:38:11.230

2

PARI/GP, 26 bytes

Simple solution:

forprime(p=2,1e6,print(p))

Less-efficient solutions, one per line:

prodeuler(p=2,1e6,print(p));
apply(n->print(n),primes(78498));
apply(n->print(n),primes([2,1e6]));

Charles

Posted 2012-05-26T07:24:50.913

Reputation: 2 435

2

APL (Dyalog), 15 chars

⍪(⊢~∘.×⍨)1↓⍳1E6

Try it online! (only goes until one thousand as TIO does not allot enough memory for a million)

⍳1E6 first million ɩntegers

1↓ drop one

() apply the following tacit function:

 the argument (all the numbers 2…1000000)

~ except those that are in

∘.×⍨ the multiplication table (using the argument as both vertical and horizontal axis)

 table (makes list into column)

Adám

Posted 2012-05-26T07:24:50.913

Reputation: 37 779

2

Python, 75

print filter(lambda n:n==2 or all(n%i for i in range(2,n)),range(15485864))

Not terribly efficient though, it actually gives me a out of memory error in Jython.

Here's a (slightly) more efficient version:

import math
print [2]+filter(lambda n:all(n%i for i in xrange(3,int(math.sqrt(n))+1,2)),xrange(3,15485864,2))

This version took approximately 8 minutes to run.

Joel Cornett

Posted 2012-05-26T07:24:50.913

Reputation: 361

quite a big variety of speeds here, one of my answers took 4.5 seconds – None – 2014-05-14T16:38:31.617

2

Scala, 58

2 to 1000000 map{x=>if(2 to x/2 forall(x%_!=0))println(x)}

or

2 to 1000000 filter{x=>2 to x/2 forall(x%_!=0)}map println

Prince John Wesley

Posted 2012-05-26T07:24:50.913

Reputation: 669

Giving last prime number can save one character. – Prince John Wesley – 2012-05-27T13:28:34.173

2

Javascript es6 66 bytes

I was surprised to not see JS in here so I thought I'd put in a word for her

//takes about 19 minutes to run on my work pc
for(i=2,l=[];i<1e6;++i)l.every(a=>i/a%1)&&l.push(console.log(i)|i)

Charlie Wynn

Posted 2012-05-26T07:24:50.913

Reputation: 696

1You can save a byte by incrementing in the compare for(i=1,l=[];++i<1e6;) – andrewarchi – 2017-06-14T17:01:22.710

2

MATL, 5 bytes

1e6Zq

Explanation:

1e6   % push 10000 to stack
   Zq % primes up to top-of-stack number

Cedric Reichenbach

Posted 2012-05-26T07:24:50.913

Reputation: 448

1

Tcl, 104 bytes

set i 2
time {set p 1;set j 2;while \$j<$i {if $i%$j==0 {set p 0};incr j};if $p {puts $i};incr i} 999998

Try it online!

Unfortunately I could not find an online Tcl interpreter which does not time out running it.


Tcl, 110 bytes

set i 2
time {set p 1;set j 2;while \$j<$i {if $i%$j==0 {set p 0;break};incr j};if $p {puts $i};incr i} 999998

Try it online!

tcl, 115

set i 2
time {set p 1;set j 2;while \$j<$i {if ![expr $i%$j] {set p 0;break};incr j};if $p {puts $i};incr i} 999998

demo


tcl, 201

My still not golfed answer:

for {set i 2} {$i<$1000000} {incr i} {
    set p 1
    for {set j 2} {$j<$i} {incr j} {
        if {[expr $i%$j] == 0} {
            set p 0
            break
        }
    }

    if $p {puts $i}
}

demo

sergiol

Posted 2012-05-26T07:24:50.913

Reputation: 3 055

102 – ASCII-only – 2019-04-01T05:32:20.233

100 – ASCII-only – 2019-04-01T05:52:46.567

94 - note my previous bytecounts should be 2 longer since i lowered loop limit – ASCII-only – 2019-04-01T05:57:18.187

88 – ASCII-only – 2019-04-01T06:01:32.607

1

PHP, 100 95 bytes

It works by iterating 1,000,000 times and then using this regular expression on a unary number to check if it's prime. It's not the smallest PHP solution submitted, but thought I'd submit it just so it's here.

for($i=0;$i<=1e6;$i++)if(preg_match('/^1?$|^(11+?)\1+$/',str_repeat("1",$i))==0)echo$i.PHP_EOL;

Matchu explains how the regular expression works - https://stackoverflow.com/a/3296068/3000179

First 50: https://eval.in/746404

ʰᵈˑ

Posted 2012-05-26T07:24:50.913

Reputation: 1 426

Can you remove the space between for($i=0;$i<=1e6;$i++) and everything else? – CalculatorFeline – 2017-03-02T15:15:06.460

@CalculatorFeline yep, thanks! – ʰᵈˑ – 2017-03-02T15:47:14.123

Great algorithm! 28 bytes shorter: while(++$i<1e6)preg_match('/^1?$|^(11+?)\1+$/',$s.=1)||print"$i\n"; (not tested). Save one more byte with a literal newline. Have you tried ereg instead of preg_match? That would save another 8 bytes, shrinking your solution to 58 bytes. – Titus – 2018-03-03T02:18:50.260

1

Ohm, 3 bytes (CP437)

Non-competitive, obviously, but I don't think anyone will mind since this question is almost 5 years old ;)

6°P

Nick Clifford

Posted 2012-05-26T07:24:50.913

Reputation: 1 184

1

05AB1E, 7 bytes

Since there is not yet an answer in 05AB1E.

T6mGNp–

Try it online!

kalsowerus

Posted 2012-05-26T07:24:50.913

Reputation: 1 894

Why is the input for this 22? – Magic Octopus Urn – 2017-06-14T16:56:43.220

@carusocomputing There is no reason for that... removed it – kalsowerus – 2017-06-15T05:49:55.777

1

Haskell, 65 chars

main=print[x|x<-[2..999999::Int],null[i|i<-[2..x-1],mod x i==0]]

Ray

Posted 2012-05-26T07:24:50.913

Reputation: 1 946

Nice. Could you save a few by removing the ::Int ? – brander – 2017-03-02T04:08:04.740

1

Pyth, 12 bytes

V^T6IqlPN1N

Explanation

V^T6 - For loop using looping variable N in range 0 to 10 ^ 6

IqlPN1 - If len(prime_factors(n)) == 1

N - implicity print n (if it is prime)

Try running the code here: https://pyth.herokuapp.com/?code=V%5ET6IqlPN1N&debug=0

Note that this seems to take too long to run on the online interpreter, so try replacing V^T6 with V^T3, which will run (and clearly if it can print primes up to 1,000, it will work with 1,000,000)

Karan Elangovan

Posted 2012-05-26T07:24:50.913

Reputation: 179

Welcome to PPCG! – Martin Ender – 2017-08-12T09:59:10.660

1

Pyt, 9 bytes

78497ǰƖřᵽ

Try it online!

78498ǰƖřᵽ
78497      - push 7, 8, 4, 9, and 7 on the stack
    ǰ      - join everything on stack w/no delimiters
     Ɩ     - casts to int
      ř    - construct range from 78498 to 1 ([1,2,3,..., 78497, 78498])
       ᵽ   - push xth prime for every item in list

Doesn't meet the timeout rq on tio, but it would work, you can try it with lower numbers the reason for 78498 is that that is the 0 indexed prime under a million

FantaC

Posted 2012-05-26T07:24:50.913

Reputation: 1 425

You can save a byte (or two) and get it to not time out on tio: 6ᴇřĐṗ*žÁ. The Á is only to make the output match the format specified in the question, and can be removed if the output can be an array. – mudkip201 – 2018-03-04T14:28:35.767

I feel like that's different enough to post as your own answer, but if you don't want to, I'll update.

– FantaC – 2018-03-04T20:56:32.213

I'll post it as a separate answer – mudkip201 – 2018-03-04T20:59:37.837

1

C (gcc) 65 bytes

j;f(i){for(;++i<1e6;)for(j=2;!printf("%d\n"+(i>j)*3,i)&&i%j++;);}

Try it online! ( stops at 1000 )

PrincePolka

Posted 2012-05-26T07:24:50.913

Reputation: 653

159 bytes – ceilingcat – 2019-04-01T03:12:40.663

1

C - 67

$ cat x.c
main(p,t){for(p=1;t=2,++p<1e6;t<p||printf("%d\n",p))while(p%t++);}
$ wc -c x.c 
67 x.c
$ gcc -O3 x.c -o x
x.c: In function ‘main’:
x.c:1: warning: incompatible implicit declaration of built-in function ‘printf’
$ ./x | wc -l
78498

It's sloooooow... don't ask... :-D

I got an even shorter variant (54 bytes) but unluckily it prints the biggest prime first. ;-(

Maybe it fits in a different code golf... someday... ;-)

user19214

Posted 2012-05-26T07:24:50.913

Reputation:

1

Clojure - 95 bytes

This is a simple, unoptimised function which prints the primes.

(defn p[](doseq[i(range 2 1e6):when(every? false?(map #(=(mod i %)0)(range 2 i)))](println i)))

Now, I wanted to create something nice too, so here is a function that creates a lazy infinite list of primes.

(defn primes
  ([]
    (concat [2 3] (primes 5)))
  ([n]
    (lazy-seq
      (first
        (for [i     (range)
              :let  [i (+ i n)]
              :when (every? false? (map #(= (mod i %) 0)
                                        (range 2 (Math/sqrt i))))]
          (cons i (primes (+ i 2))))))))

seequ

Posted 2012-05-26T07:24:50.913

Reputation: 1 714

1

Matlab (12)

Pretty simple=)

primes(1e6)'

flawr

Posted 2012-05-26T07:24:50.913

Reputation: 40 560

So simple that there is already http://codegolf.stackexchange.com/a/6274/21348

– edc65 – 2014-08-03T16:48:45.610

Oh, didn't see that one, but I have to say that mine is way shorter=) – flawr – 2014-08-03T17:19:56.223

1

Java, 183 characters

import java.util.stream.*;
class P{public static void main(String[]a){
IntStream.range(1,1000000).filter(i->!IntStream.range(2,i).anyMatch(j->i%j==0)).forEach(System.out::println);
}}

Performance is not optimal, but code is well readable. For faster computation could be code extended to use parallel streams:

import java.util.stream.*;
class P{public static void main(String[]a){
IntStream.range(1,1000000).parallel().filter(i->!IntStream.range(2,i).anyMatch(j->i%j==0)).forEachOrdered(System.out::println);
}}

Tomáš Dvořák

Posted 2012-05-26T07:24:50.913

Reputation: 621

I think you can remove some of the newlines. – SuperStormer – 2017-06-26T22:52:27.850

1

Java - 101 characters

Ungolfed version:

for(int i=3, j; i < 1000000; i++) {
    for(j = 2; j < i / 2; j++)
        if (i % j ==0)
            break;
    System.out.printf(i % j != 0 ? i + "%n" : "");
}

Golfed version:

for(int i=3,j;i<1000000;i++){for(j=2;j<i/2;j++)if(i%j==0)break;System.out.printf(i%j!=0?i+"%n":"");}

Barracuda

Posted 2012-05-26T07:24:50.913

Reputation: 31

IDK, if that is an accepted format in Codegolf, you have to wrap it into a function, a lambda or a program. It helps other people to test your code faster and gives everyone using the same language a fair playing ground. – HopefullyHelpful – 2016-05-26T14:13:51.583

@Martin Büttner Oups. Fixed it. – Barracuda – 2014-08-04T21:20:58.287

1

Perl6 - 47

for 1..10**6 {(1 x$_)~~/^(11+?)$0+$/ or say $_}

credit to Gowtham's perl solution

  • 1000000 better written as 10**6
  • print "$_\n" became say $_
  • =~ became ~~
  • needed to add whitespace in front of the x operator

pabo

Posted 2012-05-26T07:24:50.913

Reputation: 111

you can use superscript version of 106 > 10⁶ so you can shorten range from 1..106 to ^10⁶

  • you can move the for on the right side and it becomes 41 chars

(1 x$_)~~/^(11+?)$0+$/ or say $_ for ^10⁶ – Demayl – 2017-06-15T07:00:12.407

You could also use .say instead of say $_. – bb94 – 2019-04-19T03:56:51.120

1

Dart - 75 chars

Loop based version:

main(i,j){for(i=2;i<1e6;i++)l:{for(j=2;j<i;j++)if(i%j<1)break l;print(i);}}

It's much faster if you change j<i to j*j<=i, but not shorter!

Alternative List based version (107 chars) Not going to win any records without a shorter way to generate the list.

main(p,q){p=new List.generate(999998,(x)=>x+2);while(!p.isEmpty){print(q=p[0]);p.removeWhere((x)=>x%q<1);}}

Ungolfed

    main(p,q) { 
      p = new List.generate(999998, (x) => x + 2);
      while (!p.isEmpty) { 
        print(q = p[0]);
        p.removeWhere((x) => x%q < 1);
      }
    }

lrn

Posted 2012-05-26T07:24:50.913

Reputation: 521

1

Bacchus, 34 bytes

\n[2..1E6]a(Öp:a(·=1.Öw)?),·¨

Explanation:

\n            Prepare the output to be one in each line

[2..1E6]      Generates an array from 2 to 1000000

:a            Push the array to the stack

(),·¨         For each element on the array we previously pushed to the stack

Öp:a          If current element of the for-each loop is Prime push 1 to the stack. Otherwise, push 0.

(·=1.Öw)?     If last pushed element is 1 then print current element of the for each loop.

Most of the code is used to output each prime in different lines. Otherwise a much shorter code (10 bytes) would be

[2..1E6]p#

Averroes

Posted 2012-05-26T07:24:50.913

Reputation: 3 771

1

LiveScript - 71 bytes

I was goofing around, trying to golf Sieve of Eratosthenes. I'm quite happy with the result. It uses prelude.ls.

x=1e6;[2 to x]|>unfoldr ([x]:l)->|l>[]=>[console.log<|x,l|>filter (%x)]

It outputs to the console. You can try the code in http://livescript.net - I recommend using lower limit than 1e6, because it gets slow at those numbers and probably hangs your browser for a while. I couldn't find a way to stop LS from inlining [2 to 1e6], so I had to creae a var for it.

Just for the sake of it, the original function I mangled the first one from:

p=->[2 to it]|>unfoldr ([x]:l)->|l>[]=>[x,l|>filter (%x)]

seequ

Posted 2012-05-26T07:24:50.913

Reputation: 1 714

1

JS, 100 67 57

By xem and subzey

Execute this in the browser's console or nodeJS.

Short version: 57b. (it's very long to end: ~ 20 min)

for(i=1;1e6>++i;p&&console.log(i))for(p=j=i;j-->2;)p*=i%j

Faster version, 100b (ends in ~ 1 min)

p=[];for(i=2;1E6>i;i++)for(t=0,j=i;1E6>j;j+=i)t&&(p[j]=1),t=1;for(i=2;1E6>i;i++)p[i]||console.log(i)

xem

Posted 2012-05-26T07:24:50.913

Reputation: 5 523

1

Prolog - 129

Not a very short variant, but reasonably fast. A simple implementation of the Sieve of Eratosthenes.

:-initialization m.
F+S+X:-G is F,(G=<1e6,X=G;G<1e6,(G+S)+S+X).
m:-assert(i-1),2+1+I,\+i-I,write(I),nl,I*I+I+J,assert(i-J),1=0;!.

Invocation:

time swipl -qf ./prime.pl < /dev/null | wc -l

78498

real    0m3.646s
user    0m3.468s
sys     0m0.264s

Readable:

:- initialization(main).

between2(From, _, X) :-
    X is From,
    X =< 1000000.
between2(From, StepSize, X) :-
    Y is From,
    Y < 1000000,
    between2(Y + StepSize, StepSize, X).

main :-
    assert(stroke(1)), % shorter than ":-dynamic stroke/1."
    between2(2, 1, I),
    \+ stroke(I),
    write(I), nl,
    between2(I*I, I, J),
    assert(stroke(J)),
    fail.
main.

kay - SE is evil

Posted 2012-05-26T07:24:50.913

Reputation: 230

1

Perl, 75

map{my($a,$b)=($_,0);for(2..$a-1){$a%$_==0&&$b++}$b||print"$a\n"}(2..10**6)

KSFT

Posted 2012-05-26T07:24:50.913

Reputation: 1 527

1

Pyth - 14 12 chars

Fkr2^T6IqlPk1k

Thanks so much to @FryAmTheEggman for removing two chars from filter and ![1:] instead of ==1. As you probably can guess I learned Pyth literally yesterday. :)

jbf!tPTtU^T6

Omg I actually beat Mathematica builtins. Its very simple it just loops through 2 to a million and uses trick that prime numbers have one number in thier prime factorization which pyth happens to have a function for.

jb:    Join with \n as sperator
f:     filter by
!tPT:  not tail of prime factorization of loop variable(tail would be falsey if len 1 so then negate)
tU^T6:  filter through range 2-million

It does take a verrrrrry long time to run, but if you want to just see it run, you can change the 6 to a 2 for primes under hundred.

Maltysen

Posted 2012-05-26T07:24:50.913

Reputation: 25 023

Using pyth's filter function is a tad shorter: jbf!tPTtU^T6. This also saves a char by checking len(prime_factors(n)[1:])>0, which could also be added to your code: I!tPk. (This works because an empty list is False, and a list of any other length is True) Good luck with Pyth ;) – FryAmTheEggman – 2014-12-30T05:33:07.417

1

Jagl Alpha 1.2 - 14 bytes

Not competing, language is younger than question

1e6r{m}%{PZp}/

Prints on separate lines.

globby

Posted 2012-05-26T07:24:50.913

Reputation: 1 132

Is this language younger than the question? – trichoplax – 2014-12-30T00:27:03.597

Yes, I am not competing. Clarified in the answer @githubphagocyte – globby – 2014-12-30T00:27:37.753

@githubphagocyte :) – globby – 2014-12-30T00:33:33.120

1

Ruby 37 32

(2..1e6).map{|x|p x if x.prime?}

shivam

Posted 2012-05-26T07:24:50.913

Reputation: 111

yeah that makes so much sense. THanks :) – shivam – 2015-03-09T12:35:17.433

Actually, I can't find any documentation of prime?. Have you tested this? – Martin Ender – 2015-03-09T12:38:34.103

yeah it works great. Here: http://ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Integer.html#method-i-prime-3F

– shivam – 2015-03-09T12:40:00.490

This only works if the Prime module is loaded. You need to require 'prime' otherwise you get NoMethodError: undefined method \prime?' for 2:Fixnum` – daniero – 2015-09-03T17:38:31.120

1

T-SQL, 141

Assuming a resultset is valid output, here's code that works with SQL Server 2008 R2. It uses a table to store previously found primes. The table is initialized with 2, and all odd integers greater than that are checked against the contents of the table at the point in time of the check. Runtime and efficiency obviously were not concerns....

DECLARE @ INT=3SELECT 2 p INTO # l:IF NULL=ALL(SELECT 1FROM # WHERE @%p=0)INSERT # VALUES(@)SET @+=2IF @<1e6GOTO l SELECT p FROM # ORDER BY p

Muqo

Posted 2012-05-26T07:24:50.913

Reputation: 499

1

Sage, 28 bytes

for i in primes(1e6):print i

Try it online

Mego

Posted 2012-05-26T07:24:50.913

Reputation: 32 998

@FryAmTheEggman It's Python 2 – Mego – 2016-04-27T19:05:15.513

1

Pyth, 9 bytes

V^T6IP_NN

Explanation:

V starts a for loop from 0 to the next number, keeping N as the value
T = 10 and so ^T6 = 10^6 = 1000000
I is if, P_N checks if N is prime and returns True or False based on the result.
The final N is just to print it.

I'm new to Pyth so it's likely not the best solution. Any suggestions are welcome!

Hunter VL

Posted 2012-05-26T07:24:50.913

Reputation: 321

1

Java 8, 100 97 92 bytes

o->{for(int i=1,n,j;i++<1e6;){for(n=i,j=2;j<n;n=n%j++<1?0:n);if(n>1)System.out.print(n);}}

-3 bytes by thanks to @Nevay.
-5 bytes by converting Java 7 to Java 8.

I know there are already a few other Java answers. I didn't knew which to choose to put the comment on with my golfed method, so I decided to post this separate answer. Not to mention it's slightly or a lot shorter than any of the other current Java answers so far.

Explanation:

Try it here.

o->{                          // Method with empty unused parameter and no return-type
  for(int i=1,n,j;            //  Initialize some integers
      i++<1e6;){              //  Loop (1) from 2 through 1,000,000 (exclusive)
    for(n=i,j=2;              //   Set some integers
        j<n;                  //   Inner loop (2) from 2 through `n` (exclusive)
      n=                      //    Change `n` to:
        n%j++<1?              //     If `n` is divisible by `j`:
         0                    //      Change `n` to 0 (which means it isn't a prime)
        :                     //     Else:
         n                    //      Leave `n` unchanged
    );                        //   End of inner loop (2)
    if(n>1)                   //   If `n` is larger than 1, which means it's a prime:
      System.out.println(n);  //    Print `n` + new-line
  }                           //  End of loop (1)
}                             // End of method

Kevin Cruijssen

Posted 2012-05-26T07:24:50.913

Reputation: 67 575

2You can use if(n>1)System.out.println(n); instead of System.out.print(n>1?n+"\n":""); to save 3 bytes. – Nevay – 2017-08-11T12:39:14.400

0

Ruby, 60 bytes

for n in 0..1e6
if('1'*n)!~/^1?$|^(11+?)\1+$/
puts n
end
end

see here for explanation

Selim

Posted 2012-05-26T07:24:50.913

Reputation: 101

@WheatWizard thanks, fixed now! – Selim – 2017-03-02T16:24:14.773

0

Haskell, 126 chars, Using Sieve of Eratosthenes

import Data.Set 
g i n m|i>n=[]|member i m=g(i+1)n m|1<2=i:g(i+1)n(fromList[i*i,i*i+i..n]`union`m)
main=print$g 2(10**6)empty

Run quite fast on my machine.

% ghc primeList1.hs -O
[1 of 1] Compiling Main             ( primeList1.hs, primeList1.o )
Linking primeList1 ...

% time ./primeList1 >/dev/null
./primeList1 > /dev/null  5.04s user 0.05s system 99% cpu 5.100 total

Ray

Posted 2012-05-26T07:24:50.913

Reputation: 1 946

0

Ruby, 94 (optimized for speed, 2.655 secs)

(a=[*2..n=1e6]).each{|p|next if !p
break if p*p>n
(p*p).step(n,p){|m|a[m]=nil}}
puts a.compact

Ran in 2.655 seconds on my machine, which is pretty good considering how slow Ruby is.

Here's how I timed it:

t = Time.now

(a=[*2..n=1e6]).each{|p|next if !p
break if p*p>n
(p*p).step(n,p){|m|a[m]=nil}}
puts a.compact

puts Time.now - t

It takes a ridiculously long time to output to stdout, so I did sieve.rb > sieve.txt (on Windows).

Doorknob

Posted 2012-05-26T07:24:50.913

Reputation: 68 138

0

Python 2 (PyPy), 86 bytes

for i in range(2,int(1e6)):
	if all([i%j!=0 for j in range(2,int(i**0.5)+1)]): print i

Try it online!

Husnain Raza

Posted 2012-05-26T07:24:50.913

Reputation: 329

0

Stax, 7 bytesCP437

ç►╪(Æ;Ç

Run and debug online!

Explanation

Uses the unpacked version to explain.

wi|6QVM<
w           loop
 i          loop index `i`
  |6        the `i`th prime
    Q       print and keep on stack
     VM<    while the printed number is less than one million

Weijun Zhou

Posted 2012-05-26T07:24:50.913

Reputation: 3 396

0

Pyt, 8 bytes

6ᴇřĐṗ*žÁ

Try it online!

Explanation:

6ᴇ            Push 1000000
ř             Push [1,2,...,999999,1000000]
Đ             Duplicate top of stack
ṗ             Is each element prime (pushes array of booleans)
*             Multiply top two on stack element-wise
ž             Remove all zeros
Á             Push contents of array onto stack
              Implicit print

mudkip201

Posted 2012-05-26T07:24:50.913

Reputation: 833

0

Microscript II, 18 bytes

6E_s{ls1+v;(lP)}*h

Requires the latest version of the interpreter due to a bug in how the previous version handled addition with null values (although in retrospect it might work even in the previous version if you change ls1+ to 1sl+).

Approximate pseudocode translation:

x=0
Repeat 10⁶ times:
    x=x+1
    if x is prime:
        print x
End

SuperJedi224

Posted 2012-05-26T07:24:50.913

Reputation: 11 342

0

(M)AWK - 104 103 100 98 97 87

BEGIN{for(n=2;n<1e6;){if(n in L)p=L[n]
else print p=n
for(N=p+n++;N in L;)N+=p
L[N]=p}}

Old:

The 'x' file:

BEGIN{for(n=2;n<1e6;){if(n in L){p=L[n]
del L[n]}else print p=n
for(N=p+n++;N in L;)N+=p
L[N]=p}}

The size:

$ wc -c x
97 x

The run (counting output lines instead of wasting space here) on a Thinkpad T60/T5500@1.6GHz in powersave mode (1 GHz clock, Debian6):

$ time mawk -f x | wc -l
78498

real    0m3.894s
user    0m3.820s
sys     0m0.072s

But since this won't be the shortest solution, speed is no matter.

The algorithm is a reorganized sieve method. I have not seen this method elsewhere up to now and the local name is "floating sieve of erathosthenes" (FSOE) until I know better.

user19214

Posted 2012-05-26T07:24:50.913

Reputation:

0

Groovy - 65 chars

This feels like cheating, but... Output confirmed against other solutions (i.e. 'probable prime' is accurate for such small values)

n=new BigInteger(1);78498.times{println n=n.nextProbablePrime()}

The code uses the fact that there are 78498 primes that fit the requirement.

Michael Easter

Posted 2012-05-26T07:24:50.913

Reputation: 585

0

C# & LinqPad 71

As usual directly executable in LinqPad

for(int i=0;++i<1e6;){for(int b=1;++b<i;)if(i%b==0)goto a;i.Dump();a:;}

Takes about 7 minutes on my computer.

EvilFonti

Posted 2012-05-26T07:24:50.913

Reputation: 301

0

Perl, 35

use ntheory":all";print_primes(1e6)

Fast and small vs. the usual golf horrifically slow regex. I used this earlier for 39 characters:

use ntheory":all";say for@{primes(1e6)}

DanaJ

Posted 2012-05-26T07:24:50.913

Reputation: 466

0

Golfscript, 55

{.2<{}{:l;1{).l\%}do}if}:r;10 6?,{..r={" "+print}{}if}%

Old code:

{:q-2:r\,{1+}%{q\%0={1r+:r}{}if}%;;r}:f 1000000,{f!},\;(;n*

WARNING. This program uses an extremely slow algorithm, it takes ~15 seconds for it to display the 1000 first primes and the time grows exponentially. If you want to use it, change the 1000000 in the code to something lower.

Loovjo

Posted 2012-05-26T07:24:50.913

Reputation: 7 357

0

><> (Fish), 54 51 bytes

11+:aa*:\/&~!
:**=?;2&\
:v?=&:&:<^!?%&+1:&
.\:nao90

There's Befunge but no ><>, so I thought "might as well". Uses the ever so slow trial division.

Sp3000

Posted 2012-05-26T07:24:50.913

Reputation: 58 729

0

Smalltalk - 22 characters

Integer primesUpTo:1e6

The dialect is Smalltalk/X; other dialects have the same or a similar method in Integer.

Exec. time (measured with: "Time millisecondsToRun:[...]" is 90ms on my somewhat older (2010) 2.6Ghz Mac.

Evaluating "(Integer primesUpTo:1e6) size" returns: 78498

blabla999

Posted 2012-05-26T07:24:50.913

Reputation: 1 869

0

Ruby, 118 117 bytes

n=999984;t=true;a=[t]*n;(2..Math.sqrt(n).round).each{|i|a[i]&&(i..n/i).each{|j|a[j*i]=!t}};(2..n).each{|i|a[i]&&p(i)}

Run Time:

0.53s user 0.13s system 92% cpu 0.714 total

Vasu Adari

Posted 2012-05-26T07:24:50.913

Reputation: 941

0

C (111)

x=1000000,s[1000000],j;main(i){while(++i<x)for(j=2*i;j<x;j+=i)
s[j]=1;for(i=1;++i<x;)if(!s[i])printf("%d\n",i);}

C (112)

x=1000000,s[1000000],j;main(i){while(++i<x)for(j=2*i;j<x;j+=i)
s[j]=1;i=1;while(++i<x)if(!s[i])printf("%d\n",i);}

C (113, over 25% faster)

x=1000,s[1000000],j;main(i){while(++i<x)for(j=i*i;j<x*x;j+=i)
s[j]=1;i=1;while(++i<x*x)if(!s[i])printf("%d\n",i);}

C (ungolfed)

#include <stdio.h>
int sieve[1000000];
int main(void) {
    int i, j;
    for (i = 2; i < 1000; i++)
        for (j = i * i; j < 1000000; j += i)
            sieve[j] = 1;
    for (i = 2; i < 1000000; i++)
        if (!sieve[i])
            printf("%d\n", i);
    return 0;
}

Delan Azabani

Posted 2012-05-26T07:24:50.913

Reputation: 693

i=1;while(++i<E) can be improved to for(i=1;++i<E;). for(j=2*i;j<x;j+=i)s[j]=1; can be improved to for(j=1;++j<x;)s[j*i]=1; – Peter Taylor – 2012-05-26T08:48:47.627

Thanks. For your second improvement, though, considering that j would no longer be a direct index to the sieve, wouldn't comparing against x cause the program to significantly overrun the array? – Delan Azabani – 2012-05-26T08:54:12.767

Fair point. One big improvement still possible, though: use a single loop. Can't think how I missed it earlier. – Peter Taylor – 2012-05-26T09:40:44.173

As in, using one loop in total, or replacing the first pair of loops with one loop, resulting in two loops? I don't think the former is possible, as it'd mean printing while the sieve is in an incomplete state. – Delan Azabani – 2012-05-26T09:42:48.760

Sure it's possible. The part of the sieve up to i is complete. – Peter Taylor – 2012-05-26T10:59:15.853

If you moved the declaration of s inside the loop you could use x instead of 1000000, I think you could save a character or two even taking the additional int and ; into account. – Gareth – 2012-05-26T11:31:43.497

Can't you do x=1000000,s[x]? I'm not an expert in C though. – Bálint – 2016-04-27T18:53:05.863

Also, instead of s[j]=1;for(i=1..., do s[j]=i=1;for(... – Bálint – 2016-04-28T12:38:06.223

You can probably just use 1e6 rather than 1000000 in most contexts. It's a floating-point number rather than an integer, but it tends to get implicitly converted. – None – 2016-11-14T05:28:52.087

0

Python, 68

print[a for a in range(2,999999)if all(a%b for b in range(2,a/2+1))]

Sadly, there's no hope in seeing it terminate within any reasonable time frame...

edwkar

Posted 2012-05-26T07:24:50.913

Reputation: 21

0

Swift 2, 79 bytes

Utilises the Sieve of Eratosthenes.

var r=[Int](2..<Int(1e6));while r.count>0{print(r[0]);r=r.filter{$0%r[0] != 0}}

Notes:

  • Solution without the sieve needs two extra bytes.
  • Takes ~14 mins on i5 3.5 GHz; or ~40 secs if compiled with optimisations.
  • Use -O flag with swiftc to turn on optimisations.

Hitster GTD

Posted 2012-05-26T07:24:50.913

Reputation: 1

0

Molecule (v6+), 19 bytes (non-competing)

0{1+_p?~}u1000000L

Explanation:

0{1+_p?~}u1000000L
0{1+_p?~}          Push 0, add a code block.
         u1000000  Push one million.
                 L Repeat the code block 1000000 times.

user47018

Posted 2012-05-26T07:24:50.913

Reputation:

Since this language postdates the challenge by nearly 4 years, I've marked this submission as non-competing – Mego – 2016-04-27T09:00:55.763

0

Oracle SQL 11.2, 139 bytes

WITH v AS(SELECT LEVEL i FROM DUAL CONNECT BY LEVEL<=:1)SELECT a.i FROM v a, v b GROUP BY a.i HAVING:1-2=SUM(SIGN(MOD(a.i,b.i)))ORDER BY 1;

Jeto

Posted 2012-05-26T07:24:50.913

Reputation: 1 601

0

Java 107 Bytes, 26 minutes, naive approach

y->{int i=1,j,n,r=0;for(j=2,n=1000000;(r+=++i>=j?1:0)!=n;j+=j%i==0?i=1:0)System.out.print(i>=j?j+"\n":"");}

ungolfed

                y->{
                int i=1,j,n,r=0;
                for(j=2,n=1000000; 
                    (r+=((++i>=j)?1:0))!=n; 
                    j+=((j%i==0)?i=1:0)) {
                    System.out.print(i>=j?j+"\n":"");
                }
                }

Worstcase Runtime is O(n) divisons for primes as it tests everything in [2,i[ and looks if anything divides i and prints it if it's divisorless or continues if a divisor is found. n*O(n) would make it O(n^2), but due to distribution of divisors and primes, it is something along O(n^2/log(n))+O(n*log(n)) divisons. In practice this takes something along 26 minutes apparently.

Java ungolfed 1601 Bytes, adaptive wheel sieve, 1.6 seconds

public class Sieve {
    ArrayList<Integer> primes = new ArrayList<>();
    ArrayList<Integer> candidates = new ArrayList<>();
    int target = Integer.MAX_VALUE;
    int product = 1;
    int nextEvolve = 0;
    int multiplier = 1;
    int iteration = 0;
    boolean evolve = true;
    Sieve(int n) {
        this.candidates.add(1);
        this.target = n;
    }
    int next() {
        final int toTest = this.product*this.multiplier+this.candidates.get(this.iteration);
        //System.out.println("try: "+toTest+" p:"+this.product+" m:"+this.multiplier+" i:"+this.iteration);
        for(int i = this.nextEvolve; i < this.primes.size() && toTest/this.primes.get(i)>=this.primes.get(i); ++i) {
            if(toTest%this.primes.get(i)==0) {
                ++this.iteration;
                if((this.iteration%=this.candidates.size())==0) {
                    ++this.multiplier;
                }
                return this.next();
            }
        }
        this.primes.add(toTest);
        ++this.iteration;
        if((this.iteration%=this.candidates.size())==0) {
            ++this.multiplier;
            if(this.evolve && this.multiplier%this.primes.get(this.nextEvolve)==0) {
                if(this.target/this.product<toTest) {
                    this.evolve = false;
                }else {
                    final int size = this.candidates.size();
                    for(int i = 1; i < this.primes.get(this.nextEvolve); i++) {
                        for(int j = 0; j < size; j++) {
                            if((i*this.product+this.candidates.get(j))%this.primes.get(this.nextEvolve)!=0) {
                                this.candidates.add(i*this.product+this.candidates.get(j));
                            }
                        }
                    }
                    this.product*=this.primes.get(this.nextEvolve);
                    this.multiplier=this.multiplier/this.primes.get(this.nextEvolve);
                    ++this.nextEvolve;
                }
            }
        }
        return toTest;
    }
    public static void main(String[] args) {
        try {
            System.in.read();
        } catch (final IOException e) {
            e.printStackTrace();
        }
        final Sieve s = new Sieve(1_000_000);
        for(int prime = s.next(); prime < 1_000_000; prime = s.next()) {
            System.out.println(prime);
        }
    }
}

Java golfed 883 Bytes, 16 seconds

class S{ArrayList<Integer> p=new ArrayList<>(),c=new ArrayList<>();int t,q,n,m,i;boolean e=true;S(int n){this.c.add(1);this.t=n;q=m=1;n=i=0;}int next(){int toTest=this.q*this.m+this.c.get(this.i);for(int i=this.n;i<this.p.size();++i)if(toTest%this.p.get(i)==0){++this.i;if((this.i%=this.c.size())==0)++this.m;return this.next();}this.p.add(toTest);++this.i;if((this.i%=this.c.size())==0){++this.m;if(this.e && this.m%this.p.get(this.n)==0){if(this.t/this.q<toTest) this.e=false;else{int size=this.c.size();for(int i=1;i<this.p.get(this.n);i++)for(int j=0;j<size;j++)if((i*this.q+this.c.get(j))%this.p.get(this.n)!=0)this.c.add(i*this.q+this.c.get(j));this.q*=this.p.get(this.n);this.m=this.m/this.p.get(this.n);++this.n;}}}return toTest;}public static void main(String[] args){S s=new S(1_000_000);for(int prime=s.next();prime<1_000_000;prime=s.next()){System.out.println(prime);}}}

HopefullyHelpful

Posted 2012-05-26T07:24:50.913

Reputation: 208

0

Pyth, 9 bytes

V^T6IP_NN

Try it online!

Explanation:

V   : Iterate over all numbers from 0 to ...  
^T6 : 10^6
I   : If ...  
P_N : number is prime ...  
N   : print number

John Red

Posted 2012-05-26T07:24:50.913

Reputation: 151

0

Vim, 34 bytes

6@=9<CR>o<Tab>0<Esc>V{g<C-A>dj=:g/\v^(<Tab><Tab>+)\1+</d<CR>

This is a direct adaptation of my top solution to Prime Numbers. The difference is... here I have to go up to a million. This forces a cool tactic to put 999999 into the readahead, but it also makes this solution impossible to run. You won't even get past the setup making the number array, because you'd need to fill more than half a terabyte of RAM (without overhead). And if you ever got to the regex algorithm... well, it sucks. You'd never finish.

This solution requires :set autoindent noexpandtab, which you might have set already, might not. It also requires computer hardware that doesn't exist.

  • 6@=9<CR>: Cool trick to write 999999 in 5 bytes. Integer 9 gets evaluated into the expression register as text. That "macro" is run 6 times.
  • o<Tab>0<Esc>: Make N (999,999) lines of zeroes, with stair-step indent. This is kind of like what happens when you paste in insert mode without doing :set paste.
  • V{g<C-A>: Visual increment to turn the 0s into a list of numbers 1-999,999. Conveniently leaves cursor on top.
  • dj: Remove the blank (zero) and 1 lines.
  • =:: Vim users rarely think of the : command as an operator, but it is one (a charwise operator, surprisingly). Runs the = out to where the : command would move the cursor (top to bottom in this case).
  • \v^(<Tab><Tab>+)\1+<: Regex that matches a composite number of tabs. If you haven't, watch the VimCast episode, which covers an old version of this solution. The :g//d will delete those lines. The cursor will end on the last remaining line, which will act as the operator for = to remove all indent.

Vim, 36 bytes (actually runs)

  • 6@=9<CR>O0<Esc>V{g<C-A>:%norm~V$EkdYo@0D@.<C-O>@.<CR>d

This :normal macro is a proper sieve of Eratosthenes that cleans up after itself. I actually ran this out to 1,000,000. Took 10-15 minutes. The algorithm is quite good, but the data structure (array of lines in Vim) comes with a big toll. I wrote about it in more detail a long time ago.

udioica

Posted 2012-05-26T07:24:50.913

Reputation: 2 381

0

Stata, 21 bytes

primes 1000000, clear

This is (obviously) a built-in command...

f1rstguess

Posted 2012-05-26T07:24:50.913

Reputation: 181

0

ASMD, 7 bytes (non-competing)

W(i|P?p

Explanation:

W        # Push 1,000,000
 (       # Begin range loop (0 -> 999,999)
  i      # Push counter variable
   |     # Duplicate
    P?p  # If prime, print
       . # Implicit end range loop

Oliver Ni

Posted 2012-05-26T07:24:50.913

Reputation: 9 650