C++ 代码证明正整数因子最大值不超过其平方根
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime(int num) {
if (num < 2) return false;
int limit = sqrt(num);
for (int i = 2; i <= limit; i++) {
if (num % i == 0) return false;
}
return true;
}
int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
bool has_other_factor = false;
int limit = sqrt(num);
for (int i = 2; i <= limit; i++) {
if (num % i == 0) {
has_other_factor = true;
if (is_prime(i)) {
cout << i << ' is a prime factor of ' << num << endl;
} else {
cout << i << ' is a composite factor of ' << num << endl;
}
}
}
if (!has_other_factor) {
cout << num << ' is a prime number.' << endl;
} else {
cout << "All other factors of " << num << " are not greater than " << limit << endl;
}
return 0;
}
输入一个正整数 num,程序会检查 num 是否为质数,如果不是,会输出所有 num 的因子,其中质因子用 'is a prime factor' 输出,合数因子用 'is a composite factor' 输出,并且会判断所有因子是否都小于等于 sqrt(num)。
原文地址: https://www.cveoy.top/t/topic/lDyu 著作权归作者所有。请勿转载和采集!