首页 > 学院 > 开发设计 > 正文

1059. Prime Factors (25)

2019-11-10 17:06:05
字体:
来源:转载
供稿:网友

Given any positive integer N, you are supposed to find all of its PRime factors, and write them in the format N = p1^k1 * p2^k2 *…*pm^km.

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

#include<cstdio>#include<cmath>const int maxn=100010;//因为题目说在int范围内(10^9)的正整数进行质因子分解,因此素数表大概开10^5就可以了 bool isPrime(int x){ bool flag=true; if(x<=1) flag=false; for(int i=2;i*i<=x;i++){ if(x%i==0){ flag=false; break; } } return flag;}int prime[maxn],pNum=0;void findPrime(){ for(int i=2;i<maxn;i++){ if(isPrime(i)){ prime[pNum++]=i; } }}//本来想用个HashTable[],下标存放质因子,值存其个数,如HashTable[5]=4,即4个5,//但输出时不方便,必须开一个int范围的数组(n=10^9),且要遍历全部元素, struct factor{ int x,cnt;//x为质因子,x为其个数 }fac[10];//int型(10^9)范围内的数,不同质因子数不可能超过10个, //因为对于x=2*3*5*7*11*13*17*19*23*29,x有十个质因子,x已超出int范围,即一个数若有十个不同质因子,它一定大于等于x,超出int范围 int main(){ findPrime(); int n,num=0;//num为n的不同质因子个数 scanf("%d",&n); if(n==1) printf("1=1/n"); else{ printf("%d=",n); int sqr=(int)sqrt(n); for(int i=0;i<pNum&&prime[i]<=sqr;i++){ if(n%prime[i]==0){ fac[num].x=prime[i]; fac[num].cnt=0; while(n%prime[i]==0){ fac[num].cnt++; n/=prime[i]; } num++; } if(n==1) break; } if(n!=1){//如果无法被根号n以内的质因数除尽,如38=2*19,根号n为6<x<7,循环结束时n=19 fac[num].x=n; fac[num++].cnt=1; } for(int i=0;i<num;i++){ printf("%d",fac[i].x); if(fac[i].cnt>1){ printf("^%d",fac[i].cnt); } if(i<num-1) printf("*"); } } return 0;}
上一篇:CTK框架介绍

下一篇:继承与派生(二)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表