poj 3006 Dirichlet's Theorem onArithmetic Progressions
Dirichlet's Theorem on Arithmetic Progressions
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 19133 | Accepted: 9609 |
Description
If a and d arerelatively prime positive integers, the arithmetic sequence beginningwith a and increasing by d, i.e., a, a + d, a +2d, a + 3d, a + 4d, ...,contains infinitely many prime numbers. This fact is known as Dirichlet'sTheorem on Arithmetic Progressions, which had been conjectured by Johann CarlFriedrich Gauss (1777 - 1855) and was proved by Johann Peter Gustav LejeuneDirichlet (1805 - 1859) in 1837.
For example, thearithmetic sequence beginning with 2 and increasing by 3, i.e.,
2, 5, 8, 11, 14,17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74,77, 80, 83, 86, 89, 92, 95, 98, ... ,
containsinfinitely many prime numbers
2, 5, 11, 17, 23,29, 41, 47, 53, 59, 71, 83, 89, ... .
Your mission,should you decide to accept it, is to write a program to find the nthprime number in this arithmetic sequence for given positive integers a, d,and n.
Input
The input is asequence of datasets. A dataset is a line containing three positiveintegers a, d, and n separated by aspace. a and d are relatively prime. You mayassume a <= 9307, d <= 346, and n <=210.
The end of theinput is indicated by a line containing three zeros separated by a space. It isnot a dataset.
Output
The output shouldbe composed of as many lines as the number of the input datasets. Each lineshould contain a single integer and should never contain extra characters.
The output integercorresponding to a dataset a, d, n shouldbe the nth prime number among those contained in the arithmeticsequence beginning with a and increasing by d.
FYI, it is knownthat the result is always less than 106 (one million) underthis input condition.
Sample Input
367 186 151
179 10 203
271 37 39
103 230 1
27 104 185
253 50 85
1 1 1
9075 337 210
307 24 79
331 221 177
259 170 40
269 58 102
0 0 0
Sample Output
92809
6709
12037
103
93523
14503
2
899429
5107
412717
22699
25673
涉及素数的题目貌似没有什么好办法,直接打印素数用的时候再取出来即可。
打表参考:http://blog.youkuaiyun.com/dinosoft/article/details/5829550
代码:
//poj 3006 Dirichlet's Theorem on Arithmetic Progressions
#include <cstdio>
#include <cstring>
constint max=1000500;
bool is_prime[max];
int prime[max];
int top=0;
void intitPrime(){
memset(is_prime,true,sizeof is_prime);
for(int i=2; i<max; i++){
if(is_prime[i])
prime[top++]= i;
for(int j=0; j<top&&i*prime[j]<max; j++){
is_prime[i*prime[j]]=false;
if(i%prime[j]==0)break;
}
}
}
int main(int argc,charconst*argv[])
{
intitPrime();
freopen("in.txt","r", stdin);
int a, b, n;
while(scanf("%d %d%d",&a,&b,&n)!= EOF &&(a| b| n)){
int i;
for(i= a; i< max&&n>0; i += b){
if(is_prime[i]) n--;
}
printf("%d\n", i);
}
return0;
}