引用:https://zh.wikipedia.org/wiki/%E7%B4%A0%E6%95%B0
質數(Prime number),又稱素數,指在大於1的自然數中,除了1和該數自身外,無法被其他自然數整除的數(也可定義爲只有1與該數本身兩個正因數的數)。大於1的自然數若不是素數,則稱之爲合數(也稱爲合成數)。例如,5是個素數,因爲其正約數只有1與5。而6則是個合數,因爲除了1與6外,2與3也是其正約數。算術基本定理確立了素數於數論裏的核心地位:任何大於1的整數均可被表示成一串唯一素數之乘積。爲了確保該定理的唯一性,1被定義爲不是素數,因爲在因式分解中可以有任意多個1(如3、1×3、1×1×3等都是3的有效約數分解)。
常用素數判斷模板:
#include <iostream>
#include <cmath>
using namespace std;
inline bool is_prime(int radix) {
if (radix == 1) return false;
for (int i = 2; i <= sqrt(radix); ++i)
if (!(radix % i)) return false;
return true;
};
int main(int argc, char *argv[]) {
ios::sync_with_stdio(false);
int digit; cin >> digit;
if (is_prime(digit)) cout << "YES";
else cout << "NO"; cout.put('\n');
return 0;
};
線性優化:
#include <iostream>
#include <cmath>
using namespace std;
inline bool is_prime(const int radix) {
if(radix == 1) return false;
if(radix == 2 || radix == 3) return true;
if(radix % 6 != 1 && radix % 6 != 5) return false;
for(int i = 5; i <= sqrt(radix); i += 6)
if(radix % i == 0 || radix % (i + 2) == 0) return false;
return true;
};
int main(int argc, char *argv[]) {
ios::sync_with_stdio(false);
int digit; cin >> digit;
if (is_prime(digit)) cout << "YES";
else cout << "NO"; cout.put('\n');
return 0;
};