#36698: 正解


samlin961112@gmail.com (林哲甫)

學校 : 新北市私立南山高級中學
編號 : 220506
來源 : [219.70.213.92]
最後登入時間 :
2024-05-06 16:41:02
e795. p2.質數日 -- 2019年12月TOI新手同好會 | From: [219.70.213.92] | 發表日期 : 2023-08-03 16:59

大概就是先以超厲害的方法找出1-30000000的所有質數

輸入用string,之後再用substr和stoi檢查

#include <bits/stdc++.h>

using namespace std;

vector<bool> sieveOfAtkin(int limit) {
  vector<bool> isPrime(limit + 1, false);

  // 2 和 3 是質數
  if (limit >= 2) {
    isPrime[2] = true;
  }
  if (limit >= 3) {
    isPrime[3] = true;
  }

  int sqrtLimit = sqrt(limit);
  for (int x = 1; x <= sqrtLimit; x++) {
    for (int y = 1; y <= sqrtLimit; y++) {
      int n = 4 * x * x + y * y;
      if (n <= limit && (n % 12 == 1 || n % 12 == 5)) {
        isPrime[n] = !isPrime[n];
      }

      n = 3 * x * x + y * y;
      if (n <= limit && n % 12 == 7) {
        isPrime[n] = !isPrime[n];
      }

      n = 3 * x * x - y * y;
      if (x > y && n <= limit && n % 12 == 11) {
        isPrime[n] = !isPrime[n];
      }
    }
  }

  for (int n = 5; n <= sqrtLimit; n++) {
    if (isPrime[n]) {
      for (int k = n * n; k <= limit; k += n * n) {
        isPrime[k] = false;
      }
    }
  }

  return isPrime;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  vector<bool> isPrime = sieveOfAtkin(30000000);
  int d;
  cin >> d;
  string n;
  while (d--) {
    cin >> n;
    cout << n;
    bool f=false;
    for (int i = 0; i < n.length(); i++) {
      if (!isPrime[stoi(n.substr(i))]) {
        cout << " isn't a Prime Day! \n";
        f=true;
        break;
      }
    }
    if(!f){
    cout << " is a Prime Day! \n";
    }
  }
}

 
ZeroJudge Forum