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
----------------------------------这是题目和解题的分割线----------------------------------
思路:对于一个正整数来说,如果存在1和本身之外的因子,那么一定是在sqrt(n)的左右成对出现。而这道题是质因子,
因此有这样一个结论,如果正整数n存在[2,n]范围内的质因子,那么这些质因子全部小于等于sqrt(n) (因子成对出现而
质数一般更小),或者只存在一个大于sqrt(n)的质因子,其余全部小于。
#include<stdio.h>
#include<math.h>
struct node
{
int x,cnt; //x质因子,cnt个数
}s[10];
int isPrime(int x)
{
if(x<=1) return 0; //1不是质数
int sqr = (int)sqrt(1.0*x);
for(int i=2;i<=sqr;i++)
if(x%i==0) return 0;
return x; //为了方便直接返回本身了
}
int main()
{
int n,i,count = 0;
scanf("%d",&n);
printf("%d=",n);
//如果是1直接输出,这是一个测试点
if(n==1)
{
printf("1");
return 0;
}
int sqr = (int)sqrt(1.0*n);
for(i=2;i<=sqr;i++)
{
//这里&&左右不能对调,会死循环
/*如果先判断n%isPrime(i),会遇到isPrime(i)返回0的情况,
而取模不能为零。现在的顺序碰到这种情况,左边返回false,
&&直接为false,不会再去判断右边*/
if(isPrime(i)&&n%isPrime(i)==0)
{
s[count].x = i;
s[count].cnt = 0;
//由是否能整除判断个数
while(n%isPrime(i)==0)
{
s[count].cnt++;
n /= isPrime(i);
}
count++;
}
}
//n!=1说明有一个质因子大于sqrt(n),即自身
if(n!=1)
{
s[count].x = n;
s[count].cnt = 1;
count++;
}
for(i=0;i<count;i++)
{
//ki is 1 and must NOT be printed out.
if(s[i].cnt!=1)
printf("%d^%d",s[i].x,s[i].cnt);
else printf("%d",s[i].x);
if(i!=count-1) printf("*");
}
return 0;
}
该博客主要解析PAT 1059题目的内容,即如何找出一个正整数的所有质因子。博主指出,正整数的质因子要么全部小于等于其平方根,要么仅有一个大于平方根。给出的输入输出规格及样例进一步说明了题目的要求。
1879

被折叠的 条评论
为什么被折叠?



