views:

807

answers:

3

What is the shortest C code to "Calculate the n-th prime"?

Shortest in terms of significant characters, i.e. the number of semicolons, non-whitespace characters, keywords and commas.

Input:

Integers n from the standard input, separated by new lines. The input will be terminated by EOF.

Output:

Right after the input n, print the n-th prime to the standard output separated by new lines.

(You may assume the prime numbers are < 10,000, i.e. n < 1,230.)


Test cases:

Input:
    1
    2
    4
    8
    32
    999
    42
    5

Output:
    2
    3
    7
    19
    131
    7907
    181
    11

My attempt :

 #define m 10000
 a[m],b[m],x;

 main(i,j){
   for(i=2;i<m;i++)
      {
       if (!a[i])
       for (b[++x]=i,j=2*i;j<m;j+=i)
            a[j]=1;
      }
   for(;~scanf("%d",&i);printf("%d\n",b[i]));
  }

For this problem readability is not a concern.A costlier code in terms of time and memory but satisfying the constraint will be considered better here.

+2  A: 

Here's an attempt in Python. I didn't understand what exactly you meant in the input format, but this should take care of all cases. Also, it is horribly slow and takes a few seconds to generate the primes before it is ready to process input. The weird input parsing causes it to slurp in all input at once before starting to produce output so you should input numbers and end the list with an EOF and then get the answers all at once (or redirect input from a file).

import sys
p=[2]
for i in xrange(3,105000,2):
    if all(i%x for x in p):
        p.append(i)
print '\n'.join(str(p[int(i)-1]) for i in sys.stdin.read().split())

152 Characters (with spaces)

130 Characters (without spaces)

MAK
@ MAk : I am looking for a C solution only.
nthrgeek
Please state so in your question, then.
badp
+6  A: 

Mathematica: 13 characters

Prime@Input[]

The Prime function is built-in.


As a REPL: 34 characters

While[0<(s=Input[]),Print@Prime@s]

or, performing exactly 10,000 times, in 29 characters:

Print@Prime@Input[]~Do~{1*^4}
KennyTM
@KennyTM :C is must.
nthrgeek
+2  A: 

C: 104 characters

i,t,n;g(){!--n?t=1:g();for(i=++t;1<--i;i=t%i?i:t++);}main(){for(;~scanf("%d",&n);g(),printf("%d\n",t));}

(And, of course, it runs in exponential time.)

(BTW, restricting to C is boring. Most code-golf here nowadays is language-agnostic.)

KennyTM