Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
It's more common to describe the task to be completed in the question, and then provide your own solution as one of the answers. This gives you the chance to clarify the details of the task to be completed, instead of forcing us to figure them out from context. (Like, for example, the output: is it acceptable to print them out any old way, or do they have to be printed one per line? Et cetera.) – breadbox May 26 '12 at 7:49
Thanks; I've updated the question and moved my C solution to a new answer. – Delan Azabani May 26 '12 at 7:55
What is the objective? Speed? Code size? Something else? – Gaffi May 26 '12 at 8:17
Code size. I've updated the question for clarity. – Delan Azabani May 26 '12 at 8:19
6  
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. codegolf.stackexchange.com/questions/113, codegolf.stackexchange.com/questions/5087 , 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 meta.codegolf.stackexchange.com/questions/423 for criticism and discussion of how it can be improved before people start answering it. – Peter Taylor May 26 '12 at 8:42
show 1 more comment

16 Answers

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.

share|improve this answer

Bashscript (41 chars)

seq 2 1000000|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.

share|improve this answer
This can be improved to: seq 2 1000000|factor|sed 's/[0-9]*: //g;/^.* .*$/ d' – Delan Azabani May 26 '12 at 9:13
yes you're right. I wrote my sed command clean, not golfed :P – saeedn May 26 '12 at 9:15
This can also further be improved to: seq 2 1000000|factor|sed 's/[0-9]*: //g;/ /d' – Delan Azabani May 26 '12 at 9:16
I was applying this improvement before I saw your comment ;) – saeedn May 26 '12 at 9:50
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 Jun 11 '12 at 9:03
show 1 more comment

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++);}
share|improve this answer

Ruby 50 41

require'mathn'
p (2..1e6).select &:prime?
share|improve this answer
1  
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 May 26 '12 at 19:41
@Ventero thanks a lot! I didn't know about the Symbol#to_proc. I gotta pay more attention to the shortcuts Ruby offers. – w0lf May 26 '12 at 19:53

F#, 100 chars 94

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")
share|improve this answer

Golfscript 26 25

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?,{.,{)\.@%!},,2=*},`
share|improve this answer
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 May 26 '12 at 23:05
@PeterTaylor Thanks, using multiplication there is a very neat trick. – w0lf May 27 '12 at 9:42

Mathematica, 17

Just for comparison:

Prime@Range@78498
share|improve this answer

MATLAB (16)

Unfortunately, this outputs on a single line:

primes(1000000)

but that is solved by a simple matrix transpose:

primes(1000000)'

share|improve this answer

Python 3.x: 62 chars

for k in range(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)
share|improve this answer

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;
}
share|improve this answer
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 May 26 '12 at 8:48
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 May 26 '12 at 8:54
Fair point. One big improvement still possible, though: use a single loop. Can't think how I missed it earlier. – Peter Taylor May 26 '12 at 9:40
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 May 26 '12 at 9:42
Sure it's possible. The part of the sieve up to i is complete. – Peter Taylor May 26 '12 at 10:59
show 1 more comment

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.

share|improve this answer

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
share|improve this answer
Giving last prime number can save one character. – Prince John Wesley May 27 '12 at 13:28

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.

share|improve this answer
you 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) – Gajoo May 27 '12 at 11:34
@Gajet Thanks :-) – Gareth May 27 '12 at 16:00

PowerShell 52

Extremely inefficient, but the shortest I could come up with.

$p=2..999998;$p|%{$n=$_;$p=$p|?{$_-le$n-or$_%$n}};$p

PowerShell 126

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

 $p=2..999998;$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
share|improve this answer

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...

share|improve this answer

QBASIC 75 CHARS

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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