0

计算第n个素数”的最短C 代码是什么?

就重要字符而言最短,即分号、非空白字符、关键字和逗号的数量

输入:

来自标准输入的整数n,由新行分隔。输入将由 EOF 终止。

输出:

在输入n之后,将第n个素数打印到由新行分隔的标准输出。

(您可以假设素数 < 10,000,即n < 1,230。)


测试用例:

Input:
    1
    2
    4
    8
    32
    999
    42
    5

Output:
    2
    3
    7
    19
    131
    7907
    181
    11

我的尝试:

 #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]));
  }

对于这个问题,可读性不是问题。在时间和内存方面成本更高但满足约束的代码在这里会被认为更好。

4

3 回答 3

7

数学:13 个字符

Prime@Input[]

Prime功能是内置的。


作为 REPL:34个字符

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

或者,在29个字符中执行 10,000 次:

Print@Prime@Input[]~Do~{1*^4}
于 2010-02-14T10:12:41.843 回答
3

C:104 个字符

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));}

(当然,它在指数时间内运行。)

(顺便说一句,仅限于 C 很无聊。code-golf现在这里的大多数是language-agnostic.)

于 2010-02-14T16:27:15.693 回答
2

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)

于 2010-02-14T09:10:13.283 回答