Output the k-th Prime Number

本文提供了一种高效的算法来输出指定范围内的第k个素数,并优化了时间复杂度至50ms内完成计算,通过筛法优化避免重复计算,适用于大规模数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:输出第k个素数(1<=k<=10000)。

时间要求:必须在50ms内完成计算。

实现代码:



#define MAX 105000
unsigned long r[MAX],p[10000],n,t;
int main(){
int i,j,k,m;
for(i=0;i<MAX;++i) r[i]=i;
for(i=0;i<MAX;++i){
if(r[i]>1) {
for(j=2;j<MAX;++j)
if((t=i*j)<=MAX) r[t]=0;
else break;
}
}

for(m=i=0;i<MAX;++i){
if(r[i]>1) p[m++]=r[i];
if(m>=10000) break;
}

for(;~scanf("%d",&k);){
printf("%ld\n",p[k-1]);
}
}




运行结果:

[img]http://dl.iteye.com/upload/attachment/0063/3818/0858bee3-b113-36e8-83eb-2df6d49ebec7.jpg[/img]
[img]http://dl.iteye.com/upload/attachment/0063/3820/6f6bcec9-eae5-305e-9149-af9ef5a3a5c5.jpg[/img]
Sure, I understand your question. Based on the given conditions, Polycarp likes positive integers that are not divisible by 3 and do not end with the digit 3. We can generate this sequence of numbers as follows: 1, 2, 4, 5, 7, 8, 10, 11, 14, 16, 17, 19, 20, 22, 25, 28, 29, 40, 44, 46, 50, 52, 55, 58, 59, 70, 71, 74, 76, 79, 80, 82, 85, 88, 91, 94, 95, 97, 98, 100, 101, 104, 106, 107, 110, 112, 115, 118, 119, 121, ... To find the k-th element of this sequence, we can simply iterate through the sequence and stop at the k-th element. Here's the code to do that: ``` #include <iostream> #include <vector> using namespace std; bool is_disliked(int n) { return (n % 3 == 0) || (n % 10 == 3); } vector<int> generate_sequence(int n) { vector<int> seq; int i = 1; while (seq.size() < n) { if (!is_disliked(i)) { seq.push_back(i); } i++; } return seq; } int main() { int t; cin >> t; while (t--) { int k; cin >> k; vector<int> seq = generate_sequence(k); cout << seq[k-1] << endl; } return 0; } ``` The `is_disliked()` function checks if a number is disliked by Polycarp based on the given conditions. The `generate_sequence()` function generates the sequence of liked numbers by iterating through all positive integers and adding them to the sequence if they are not disliked. In the main function, we first read in the number of test cases `t`. Then we loop `t` times and for each test case, we read in the value of `k`, generate the sequence of liked numbers of length `k`, and output the k-th element of that sequence.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值