引用: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;
};