1、 使用试除法对125进行因数分解
2、 使用费马因数分解法对12345因数分解
#include<iostream>
#include<cmath>
using namespace std;
int Is_Prime(int n);
void Fac(int n);
int main() {
while (1) {
int ch;
cout << "请选择模式\n";
cout << "1.试除法\n";
cout << "2.费马因数分解\n";
cout << "3.退出\n";
cin >> ch;
if (ch == 1) {
int n;
cout << "请输入待分解的数n = ";
cin >> n;
cout << "因数分解的结果为" << n << " = ";
Fac(n);
}
if (ch == 2) {
int n, i, aim2, N;
cout << "请输入待分解的数n = ";
cin >> n;
double aim1;
for (i = 1;; i++) {
N = i * i;
aim1 = sqrt(N + n);
if (aim1 == (int)aim1) {
aim2 = i;
break;
}
}
cout << "费马因数分解找到的两个数为:" << aim1 << "," << aim2 << endl;
cout << "所以n = (" << aim1 << "-" << aim2 << ")*(" << aim1 << "+" << aim2 << ")" << endl;
if (Is_Prime(aim1 + aim2)) {
cout << aim1 + aim2 << "是素数" << endl;
}
else {
cout << aim1 + aim2 << "不是素数" << endl;
Fac(aim1 + aim2);
}
if (Is_Prime(aim1 - aim2))
cout << aim1 - aim2 << "是素数" << endl;
else {
cout << aim1 - aim2 << "不是素数" << endl;
cout << "因数分解的结果为" << aim1 - aim2 << " = ";
Fac(aim1 - aim2);
}
cout << "因数分解的结果为" << n << " = ";
Fac(n);
}
if (ch == 3) {
return 0;
}
}
system("pause");
}
int Is_Prime(int n) {
int i, num = 0;
for (i = 2; i < sqrt(n); i++) {
if (n % i == 0)
num++;
}
if (num == 0)
return 1;
else
return 0;
}
void Fac(int n) {
int i, j, N;
//N = sqrt(n) + 6;
for (i = 2; i <= n; i++) {
if (n % i == 0) {
n = n / i;
j = 1;
while (n % i == 0) {
j++;
n = n / i;
}
cout << "(" << i << "^" << j << ")";
if (n >= i) {
cout << "*";
}
}
}
cout << endl;
}