唯一分解定理

处理何种问题:对于任何一个大于1的自然数num,num可以唯一分解为有限个质数乘积,如:num=的形式。(补充:这里的唯一的意思是在不考虑排列顺序的情况下)

 

性能:时间复杂度为O(sqrt(num)) 

 

原理:唯一分解定理

 

实现步骤:类似于素数筛的求素数方法。

 

备注:当数据量大时建议先用素数筛把素数都找出来。

 

输入样例解释

54813281 //所要分解数字

982318316

 

输出样例解释

79*241*2879

2^2*7*19*23*43*1867

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
#include<cstdlib>
#include<time.h>
using namespace std;

long long p[100];//用于储存素数的幂
long long a[100];//用于储存素数

void fta(long long num,int &tot)//唯一分解定理
{
    long long prime=2;
    while(prime*prime<=num)
    {
        if(num%prime==0)
        {
            a[tot]=prime;
            p[tot]=0;
            while(num%prime==0)
            {
                ++p[tot];
                num/=prime;
            }
            ++tot;
        }
        ++prime;
    }
    if(num!=1)
    {
        a[tot]=num;
        p[tot]=1;
        ++tot;
    }
}

int main()
{
    long long num;
    int tot;//组数

    while(~scanf("%lld",&num))
    {
        tot=0;
        fta(num,tot);
        for(int i=0;i<tot;++i)
        {
            printf("%lld",a[i]);
            if(p[i]>1)
                printf("^%lld",p[i]);
            if(i!=tot-1)
                printf("*");
        }
        printf("
");
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/l1l1/p/9588288.html