1059 Prime Factors (25 分)

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805415005503488

1059 Prime Factors (25 分)

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1e6+100;
ll prime[maxn];
int num=0;
int p[maxn];
void isprime()
{
    for(int i=2; i<maxn; i++)
    {
        if(p[i]==0)
        {
            prime[num]=i;
            num++;
            for(int j=i+i; j<maxn; j+=i)
            {
                p[j]=1;
            }
        }
    }
}
struct factor
{
    int x,cnt;
} fac[100];
int main()
{
    isprime();
//    printf("%lld\n",prime[50]);
    ll n;
    scanf("%lld",&n);
    int c=0;
    ll p=n;
    for(int i=0; i<=100; i++)
    {

        if(n%prime[i]==0)
        {
            if(sqrt(1.0*n)<prime[i]) break;
            fac[c].x=prime[i];
            fac[c].cnt=0;
            while(n%prime[i]==0)
            {
                n/=prime[i];
                fac[c].cnt++;
            }
            c++;
        }
    }
    if(n!=1)
    {
        fac[c].cnt=1;
        fac[c].x=n;
        c++;
    }
    printf("%lld=",p);
    if(p==1)  /// 注意:1需要特判!!!
    {
        printf("1");
    }
    else
    {
        for(int i=0; i<c; i++)
        {
            if(fac[i].cnt>1)
            {
                printf("%d^%d",fac[i].x,fac[i].cnt);
                if(i!=c-1) printf("*");
            }
            else
            {
                printf("%d",fac[i].x);
                if(i!=c-1) printf("*");
            }
        }
    }




}

上一篇:1059:求平均年龄


下一篇:1059 C语言竞赛 (20 point(s))