1561. PRIME
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. The first prime number is 2. Can you write a program that computes the nth prime number, given a number n <= 10000?
Input
The input contains just one number which is the number n as described above.
The maximum value of n is 10000.
Output
The output consists of a single line with an integer that is the nth prime number.
Sample Input
30
Sample Output
113
【解题思路】
本题主要是求第N个素数,经典之处在于如何减少资源利用率,计算到第10000,坏的算法是不可能再一秒钟之内结束的,肯定会超时。
判定n为素数,即他不被 根号n 内的素数整除即为素数。
然后将已判定的素数存在vector中,以防止重复判定。
最后以0.05sec,312kb的运行内存计算完成,这个数据相对理想、
【遇到的问题】
判定素数的时候break过多,用错位置导致
另计数从1开始,而非从0开始,但是却有vector[0]。
【源代码】
#include<iostream> #include<vector> #include <math.h> #include <stdlib.h> using namespace std; int main() { vector <int> prime; int i=5; prime.push_back(2); prime.push_back(3); prime.push_back(5); for(;;) { i++; for(int j=0;;j++) { if(i % prime[j] == 0)break; if(prime[j] > sqrt(i)+1) { prime.push_back(i); break; } } if(prime.size()>10000)break; } int index = 0; cin>>index; cout<<prime[index-1]<<endl; return 0; }