1059 Prime Factors (25 分)
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
求素数参考链接:https://blog.csdn.net/jonms/article/details/80464622
这道题中,我们要分解一个数,即求一个数的因数(从2开始遍历),那么我们知道,当不能被一个小于sqrt(num)的数是一个素数,所以不必要遍历到这个数本身,缩小了很大的计算量,如果全部求出的话很容易超时。
其次,我们需要求出一个素数表,这里有一个很大的问题是存储素数的数组需要多大的问题,我们看题发现,要求对一个int型的数进行展开,那么我们需要是素数表中的最大数小于这个的开根号,也就是10的9次方的开根,即10的5次方(这里要注意,如果声明的数组为10的6次方时,运行会超时,所以看清这个题设还是非常重要的)
最后就是从这个素数表中选取能被这个数字整除的素数,指导素数大于sqrt(num),然后退出循环,如果剩下的部分不为1,则剩下部分为一个素数,将他保存到分解式中。
还要注意一个问题就是num==1的情况下,不要进行遍历,直接输出结果。
#include<iostream>
#include<stdio.h>
#include<vector>
#include<math.h>
using namespace std;
const int maxn = 100001;
bool isprime(int n){
int a = sqrt(n);
for(int i=2;i<a;i++)
if(n%i == 0){
return false;
}
return true;
}
int main(){
long int n;
scanf("%d",&n);
if(n == 1){
printf("1=1");
return 0;
}
vector<int> arr;
for(int i=2;i<=maxn;i++)//求出所有素数
if(isprime(i)){
arr.push_back(i);
}
bool state = 0;
int cnt = 0;
printf("%d=",n);
for(int i=0;n >= 2;i++){
cnt = 0;
while(n%arr[i] == 0)
{
n /= arr[i];
cnt++;
}
if(cnt == 0) continue;
if(state == 1)
printf("*");
state = 1;//通过state避免第一次打印符号
if(cnt == 1){
printf("%d",arr[i]);
}else{
printf("%d^%d",arr[i],cnt);
}
}
return 0;
}
或者先计算素数表:
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> prime(100001,1);
for(int i=2;i * i < 100001;i++){
//注意因为求的是素数,所以下标都是从2,这里下标是1会错误
for(int j=2;j * i < 100001;j++)
prime[i*j] = 0;
}
int n;
scanf("%d",&n);
if(n == 1){
printf("1=1");
return 0;
}
int i=2,cnt = 0;
bool state = 0;
printf("%d=",n);
for(int i=2;n >= 2;i++){
cnt = 0;
while(prime[i] == 1 && n%i==0)
{
n /= i;
cnt++;
}
if(cnt == 0) continue;
if(state == 1)
printf("*");
state = 1;//通过state避免第一次打印符号
if(cnt == 1){
printf("%d",i);
}else{
printf("%d^%d",i,cnt);
}
}
return 0;
}