PAT A 1059. Prime Factors (25)

来源:互联网 发布:农行网银mac版 编辑:程序博客网 时间:2024/05/21 22:52

题目

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

 

即求质因数分解,

由小向大扫描,依次取余判断,如果有相应的质因数项,考虑系数。

注意,输入可能是1,输入可能是质数。

 

代码:

#include <iostream>#include <cmath>using namespace std;int main(){long p[65];//存质因子int k[65]={0};//存系数long n;//输入的数cin>>n;cout<<n<<"=";if(n==1)//!!!输入可能为1{cout<<1;return 0;}long i=0;//记录非重复质因子数量long j=2;int flag=0;//获得质因子标志位,用于重新计算sqrlong sqr=sqrt((double)n)+1;//求根,计算质因子时需要的上界while(n>1){if(flag==1)//重新计算上界{sqr=sqrt((double)n)+1;flag=0;}for(;j<=sqr;j++)//从上次的位置开始扫描{if(n%j==0)//扫描到一个{p[i]=j;//记录k[i]=1;n/=j;while(n%j==0)//获取系数{n/=j;k[i]++;}i++;//刷新数据,为扫描下一个做准备j++;flag=1;break;}}if(j>sqr)//超界,意味着本身是质数{p[i]=n;k[i]=1;i++;break;}}if(k[0]==1)//输出cout<<p[0];elsecout<<p[0]<<"^"<<k[0];for(j=1;j<i;j++){if(k[j]==1)cout<<"*"<<p[j];elsecout<<"*"<<p[j]<<"^"<<k[j];}return 0;}


 

 

 

 

0 0
原创粉丝点击