写c++代码,证明一个正整数num,除了1和自身这两个因子之外,如果还有其他因子,那么这个因子最多是sqrt(num),也就是num这个数的平方根。
#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)。
原文地址: http://www.cveoy.top/t/topic/qTG 著作权归作者所有。请勿转载和采集!