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 = 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

题目大意:

给出一个整数,按照从小到大的顺序输出其分解为质因数的乘法算式

分析:

根号int的最大值不会超过50000,先建立个50000以内的素数表,然后从2开始一直判断是否为它的素数,如果是就将a=a/i继续判断i是否为a的素数,判断完成后输出这个素数因子和个数,用state判断是否输入过因子,输入过就要再前面输出。
原文链接:https://blog.csdn.net/liuchuo/article/details/52261852

题解

image
image
image

#include <bits/stdc++.h>

using namespace std;
const int maxn=100010;
//判断n是否为素数
bool is_prime(int n)
{
    if(n==1)
        return false;
    for(int i=2; i*i<=n; i++)
    {
        if(n%i==0)
            return false;
    }
    return true;
}
int prime[maxn],pNum=0;
//求素数表
void Find_Prime()
{
    for(int i=1; i<maxn; i++)
    {
        if(is_prime(i)==true)
        {
            prime[pNum++]=i;
        }
    }
}
struct factor
{
    int x,cnt; //x为质因子,cnt为其个数
} fac[10];
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    Find_Prime(); //此句请务必记得写
    int n,num=0;  //num为n的不同质因子的个数
    scanf("%d",&n);
    if(n==1)
        printf("1=1"); //特判1的情况
    else
    {
        printf("%d=",n);
        int sqr=(int)sqrt(1.0*n); //根号n
        //枚举根号n以内的质因子
        for(int i=0; i<pNum&&prime[i]<=sqr; i++)
        {
            if(n%prime[i]==0)  //如果prime[i]是n的因子
            {
                fac[num].x=prime[i]; //记录该因子
                fac[num].cnt=0;
                while(n%prime[i]==0)  //计算出质因子prime[i]的个数
                {
                    fac[num].cnt++;
                    n/=prime[i];
                }
                num++; //不同质因子个数加1
            }
            if(n==1)
                break; //及时退出循环,节省时间
        }
    }
    if(n!=1)   //如果无法被根号n以内的质因子除尽
    {
        fac[num].x=n; //那么一定有一个大于根号n的质因子
        fac[num++].cnt=1;
    }
    //按格式输出结果
    for(int i=0; i<num; i++)
    {
        if(i>0)
            printf("*");
        printf("%d",fac[i].x);
        if(fac[i].cnt>1)
            printf("^%d",fac[i].cnt);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/moonlight1999/p/15592538.html