可以做一個vector直接排除已確認是質數者的倍數
然後偶數除了2可以不用看
邊界特殊情況要處理好
要加速的話可以不要像我一樣用sqrt()
#include <iostream> #include <cmath> #include <vector> using namespace std; using std::vector; int check_prime(int num); int main(){ unsigned int start, end; while(cin >> start >> end){ vector<unsigned int> prime_list; if (start==1){ if (end == 1){ cout << 0 << endl; continue; } else{ start++; } } if ((start % 2) == 0){ if (start == 2){ prime_list.push_back(2); start++; } else{ start++; } } for(int count = start; count <= end; count = count + 2){ if (prime_list.empty()){ if (check_prime(count)){ prime_list.push_back(count); } else{ continue; } } else{ int flag1 = 1; for(int j = 0; j < prime_list.size(); j++){ if ((count % prime_list[j]) == 0){ flag1 = 0; break; } } if (flag1 == 0){ continue; } else{ if (check_prime(count)){ prime_list.push_back(count); } else{ continue; } } } } /*for(int k = 0; k < prime_list.size(); k++){ cout << prime_list[k] << endl; }*/ cout << prime_list.size() << endl; } } int check_prime(int num){ int flag = 1; for(int i = 3; i <= sqrt(num); i=i+2){ if ((num%i) == 0){ flag = 0; break; } } return flag; }