---restore content starts---
-
Describe
-
Enter a positive integer n to find the small prime number of nth.
-
Input
-
A positive integer of not more than 10000 n.
-
Output
-
The nth small prime number.
-
Sample input
-
10
-
Sample output
-
29
- Method 1: The composite must be represented as a number of times smaller than it is, so if one cannot divide all the prime numbers smaller than it, then this number is prime. Therefore, to find the nth prime number, you can start with the first n-1 prime number as the starting point, judging by the above method.
1#include <iostream>2 using namespacestd;3 intn,s;4 intp[10001]; 5 intPanintt)6 { 7 while(1) 8 { 9 BOOLok=0;Ten for(intI=1; i<=s;i++)//If it is a prime number, it must not divide all prime numbers that are smaller than it . One if(t%p[i]==0) A { -ok=1; Break; - } the if(OK) - { -t++;Continue; - } + returnT; - } + } A intMain () at { -Cin>>N; -p[1]=2; s++;//S represents the number of current prime numbers - for(intI=2; i<=n;i++) - { - intt=p[s]+1;//the next prime number is at least 1 larger than the previous prime. in intH=pan (t);//determine the next prime number -p[++s]=h; to } +cout<<P[n]; -}
- Method 2: Is the improvement of Method 1, Method 1 is the judgment can not be divided into all the smaller prime numbers, combined with the square root n complexity to determine the principle of prime numbers, such as: 15=3*5, enumeration to 3 o'clock to judge once, 5 o'clock and judge once, resulting in repeated judgment. So judging whether you can divide all the prime numbers smaller than it, you just need to judge the square root N.
#include <cstdio>#include<cmath>using namespacestd;intn,s;intp[100001];intDevide (Doublek) { intX= (int) K; for(intI=1; i<s;i++) { if(p[i]>=x)returni+1;//because the number k after the cube is forced to convert to an integer x, actually x is smaller than K, so +1 }}intMain () {scanf ("%d",&N); p[1]=2;p [2]=3; S=2; while(s<N) {intTmp=p[s];//Previous Primes++;//the current one is looking for the first s prime number. while(1) {tmp++;//at least 1 larger than the last prime number. BOOLok=false; intTest=devide (sqrt (TMP));//find out which two prime numbers are in the square after the number to be judged for(intI=1; i<=test;i++) if(tmp%p[i]==0) {OK=true; Break; } if(OK)Continue; P[s]=tmp; Break; }} printf ("%d", P[n]);}
View Code
---restore content ends---
NOI 1.5 44: Nth Small prime number