Sunday, April 5, 2020

POJ.3006 Dirichlet's Theorem on Arithmetic Progressions

1.Problem
http://poj.org/problem?id=3006

2.Idea
Sieve of Eratosthenes

3.Source
 bool isPrime[1000006];  
 vector<int> Primes;  
 int a, d, n;  
 //Sieve of Eratosthenes  
 void prep()  
 {  
      for (int i = 2; i < 1000006; i++) {  
           if (isPrime[i]==0) {  
                Primes.push_back(i);  
                for (int j = i * 2; j < 1000006; j += i) {  
                     isPrime[j] = 1;  
                }  
           }  
      }  
 }  
 int main()  
 {  
      prep();  
      while (scanf("%d%d%d", &a, &d, &n) > 0) {  
           if (a + d + n == 0) break;  
           int cnt = 0;  
           for (int i = 0; i < Primes.size(); i++) {  
                if (Primes[i] >= a && (Primes[i] - a) % d == 0) {  
                     cnt++;  
                     if (cnt == n) {  
                          cout << Primes[i] << endl;  
                          break;  
                     }  
                }  
           }  
      }  
      return 0;  
 }  

No comments:

Post a Comment