Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmkm.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N =
p1^
k1*
p2^
k2*
…*
pm^
km, where pi's are prime factors of N in increasing order, and the exponent ki is the number of pi -- hence when there is only one pi, ki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
/**
本题题意 就是给定一个数 n 此时需要判断找出该数 n 所有质因子以及它们的 个数
本题思路
1.首先求出 素性表(可以通过暴力法, 也可以通过埃拉托色尼素数筛选法求出 一个范围内的所有质数
将求出的质数放入 prime数组中 , 用 num记录数组中 质数的个数
2. 通过性质 对于一个合数的质因数
a. 全部质因子都在 sqrt(合数)的左边
b. 有一个大于sqrt(合数)在右边 其余的质素数都在该合数的左边
然后求出所有的质因子,
当 n%prime[i] == 0时 说明是质因子,(一个数有多个不同的质因子)
设定factor[i]结构体存放 不同的质因子 并记录他们的个数
while(n % prime[i] == 0)时
质因子个数 + 1,
n = n / prime[i];
**/
具体代码:
#include<iostream>
#include<cmath> //没有使用 #include<algorithm> 中的函数 有 count函数 会和 count变量冲突
using namespace std;
const int maxsize = 1e6 + 5;
int num = 0, count = 0, n, prime[maxsize]; //num记录的素数表中元素的个数,count记录素因子的个数
bool visit[maxsize];
struct factor{
int x;
int cnt;
factor(){
x = -1;
cnt = 0;
}
}fac[11]; //范围为 11是因为 11个不同的质数相乘 已经超过了 int 的范围
void find_prime(int n){ // 构建素数表
for(int i = 2; i < maxsize; i++){ //一定从2开始出发
if(i > n)
return;
if(visit[i] == false){
prime[num++] = i;
// cout << i << endl;
}
for(int j = i + i; j < maxsize; j += i){
visit[j] = true;
// cout << j << endl;
}
}
}
int main(){
scanf("%d", &n);
find_prime(n);
if(n == 1)
printf("1=1");
else{
printf("%d=", n);
// int sqr = (int)(sqrt(n));
for(int i = 0; i < num && prime[i] <= sqrt(n); i++){ //质因数判断时 此处应该是 <= 不要写出了 < 最好在外面单独定义
if(n % prime[i] == 0){
fac[count].x = prime[i];
while(n % prime[i] == 0){
n = n / prime[i];
fac[count].cnt++;
}
count++;
}
if(n == 1) //优化时间复杂度 跳出循环
break;
}
if(n != 1){
fac[count].x = n;
fac[count++].cnt = 1;
}
for(int i = 0; i < count; i++){
printf("%d", fac[i].x);
if(fac[i].cnt != 1)
printf("^%d", fac[i].cnt);
if(i != count - 1)
printf("*");
}
}
return 0;
}