1561. PRIME

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


 
 
 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值