Problem of the Day
A new programming or logic puzzle every Mon-Fri

Prime Golf

Today's problem will get us back in to the code golfing realm. Without hard coding the answers, create a program that prints out the first 100 prime numbers using the fewest characters of code (new lines count as 1 character).

Also, because it was request. The answer to Friday's problem has been posted in the comments for that problem.

Permalink: http://problemotd.com/problem/prime-golf/

Comments:

  • James - 10 years, 3 months ago

    C (106 characters):

    #include <stdio.h>
    main(){int p=2,i;for(;p<542;){for(i=2;i<p;i++)if(p%i==0)goto N;printf("%d,",p);N:p++;}}
    

    Readable:

    #include <stdio.h>
    
    int main()
    {
       int p = 2, i;
    
       for ( ; p < 542;)
       {
          for ( i = 2; i < p; i++ )
          {
             if ( p % i == 0 )
             {
                goto N;
             }
          }
          printf( "%d,",p );
       N:
          p++;
       }
    }
    

    reply permalink

  • Max Burstein - 10 years, 3 months ago

    Nicely done

    reply permalink

  • bumbleguppy - 10 years, 3 months ago

    javascript 183 characters:

     function e(n){var p=[],q=Math.sqrt(n)-2,i=1,s=[],m,j;while(i++<n)s[i-2]=i;i=-1;while(i++<=q){if(m=s[i])for(j=m*m-2;j<n-1;j+=m)s[j]=0}i=q=-1;while(i++<n-1)if(m=s[i])p[++q]=m;return p;}
    

    reply permalink

  • Anonymous - 10 years, 3 months ago

    p=[]
    i=1
    while p.length<100
     i+=1
     b=true
     b=false for n in p when i%n==0
     if b
      p.push i 
      alert i
    

    101 chars (Coffeescript)

    reply permalink

  • Dmitry - 10 years, 3 months ago

    Python (94 chars):

    filter(lambda x:x not in [i*j for i in range (2,271) for j in range(2,540/i+1)],range(2,542))
    

    reply permalink

Content curated by @MaxBurstein