题目意思:给出一个int 范围的整数,按照从小到大的顺序输出其分解为质因数的乘法算式。
题目思路:先求出质因数,不用开太大求100001以内的存到质数表中,然后输入数字在质数表里查找,记录质因数及个数。如果n最后不是1,有除不尽的质数而且没在表中,基本就是本身了。注意1的输出
//找质数,找能除的质数
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<time.h>
#include<math.h>
using namespace std;
const int maxn = 100001;
int prime[maxn] = { 0 };
bool isPrime(int n)
{
if (n == 1) return false;
int sqr = sqrt(n);
for (int i = 2; i <= sqr; i++)
{
if (n % i == 0) return false;
}
return true;
}
int pnum = 0;
void findPrime()
{
for (int i = 1; i < maxn; i++)
if (isPrime(i) == true)
prime[pnum++] = i;
}
struct factor
{
int x, count;
}fac[10];
int main()
{
findPrime();
int n, num = 0;
cin >> n;
int temp = n;
int sqr = sqrt(n);
if (n == 1)
{
cout << "1=1" << endl;
}
else
{
for (int i = 0; i < pnum && prime[i] <= sqr; i++)
{
if (n % prime[i] == 0)
{
fac[num].x = prime[i];
fac[num].count = 0;
while (n % prime[i] == 0)
{
fac[num].count++;
n /= prime[i];
}
num++;
}
if (n == 1)
break;
}
if (n != 1)
{
fac[num].x = temp;
fac[num].count = 1;
num++;
}
cout << temp << "=";
for (int i = 0; i < num; i++)
{
cout << fac[i].x;
if (fac[i].count > 1)
cout << "^" << fac[i].count;
if (i != num - 1)
cout << "*";
}
}
}