寫得有點冗長,而且在ACM居然沒過。
但在其他JUDGE過了。
找時間再來修正
- #include <iostream>
- #include <vector>
- using namespace std;
- const int MAX = 1000;
- void creat(bool* prime);
- void filter(bool*, int);
- int main()
- {
- bool prime[MAX + 1] = {};
- creat(prime);
- int n1,c;
- while(cin >> n1 >> c)
- if ( n1 == 1 )
- {
- cout << n1 << ' ' << c << ": " << "1\n" ;
- continue;
- }
- vector<int> box;
- for (int i=1; i<=n1 ; i++)
- {
- if (prime[i])
- box.push_back(i);
- }
- int len = box.size();
- if (len % 2 == 1)
- {
- if ( 2*c-1 > len)
- {
- cout << n1 << ' ' << c << ": ";
- for (int i=0; i<len; i++)
- cout << box[i] << " ";
- }
- else
- {
- int mid = len/2, begin = mid-c+1, end = mid+c-1;
- cout << n1 << ' ' << c << ": ";
- for (int i=begin; i<=end; i++)
- cout << box[i] << " ";
- }
- }
- else //len % 2 == 0
- {
- if ( 2*c > len)
- {
- cout << n1 << ' ' << c << ": ";
- for (int i=0; i<len; i++)
- cout << box[i] << " ";
- }
- else
- {
- int mid = len/2, begin = mid-c, end = mid+c-1;
- cout << n1 << ' ' << c << ": ";
- for (int i=begin; i<=end; i++)
- cout << box[i] << " ";
- }
- }
- cout << endl;
- }
- }
- //創造質數表
- void creat(bool* prime)
- {
- prime[2] = prime[3] = prime[5] = 1;
- //把6n+1、6n+5全設為質數
- int i;
- for (i=1; 6*i+5 <= MAX; i++)
- {
- prime[6*i+5] = prime[6*i+1] = 1;
- }
- if (prime[6*i+1] <= MAX)
- {
- prime[6*i+1] = 1;
- }
- //然後過濾掉6n+1、6n+5的倍數皆不為質數
- int j;
- for (j=0; (6*j+5)*(6*j+5) <= MAX; j++)
- {
- filter(prime, 6*j+5);
- filter(prime, 6*j+1);
- }
- if (prime[6*j+1] <= MAX)
- {
- filter(prime, 6*j+1);
- }
- prime[1] = 1;
- }
- //過濾掉質數的倍數
- void filter(bool* prime, int i)
- {
- if (prime[i])
- {
- for (int j=2; i*j <= MAX; j++)
- prime[i*j] = 0;
- }
- }
沒有留言:
張貼留言