练车加端盘子也挡不住我学习——质因子分解问题

质因子分解

质因子分解即为将一个正整数分解为数个质因子相乘的形式。如6=2*3。

算法思路

  • 要想分解一个正整数,首先我们当然是要先获取素数表
  • 分析可得,这个数分解方式就有两种
  1. 全部为小于等于sqrt(x)的质因数
  2. 一个大于sqrt的质因数和几个小于sqrt(x)的质因数

我们可以用一个结构体来储存每个质因数和他的个数,方便表示。

struct factor
{
    int x,cnt;//质数及个数
}

【PAT A1059】Prime Factors

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p​1​​​k​1​​​​×p​2​​​k​2​​​​×⋯×p​m​​​^k​m​​​​.

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 = p​1​​k​1​​*p​2​​k​2​​p​m​​^k​m​​, where p​i​​’s are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ – hence when there is only one p​i​​, k​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^211171011291

题目大意

题目给定一个正整数,将其质因子分解并按照题目要求的形式输出。

实现代码

#include
#include
using namespace std;
#define Max 100010
struct factor
{
    int x,cnt;//质数及个数
}fac[10];
int Pnum[Max],counts=0;//素数表及计数器
bool prime[Max]={0};
void findPrime()//埃氏筛选法
{
    for(int i=2;i<Max;i++)
    {
        if(prime[i]==false)
        {
            Pnum[counts++]=i;
            for(int j=i*2;j<Max;j+=i)
                prime[j]=true;//筛选掉非质数
        }
    }
}
int main()
{
    findPrime();
    int x,num=0;
    cin>>x;
    int sqr=(int)sqrt(1.0*x);
    if(x==1) cout<<"1=1"<<endl;//特殊情况
    else cout<<x<<"=";
    for(int i=0;i<counts&&Pnum[i]<=sqr;i++)
    {
        if(x%Pnum[i]==0)//查找质因数
        {
            fac[num].x=Pnum[i];
            fac[num].cnt=0;
        while(x%Pnum[i]==0)//如果还存在此质因子
        {
            fac[num].cnt++;
            x/=Pnum[i];
        }
        num++;
        }
        if(x==1) break;//跳出循环,节省时间
    }
    if(x!=1)//存在一个比sqr大的质数
    {
        fac[num].x=x;
        fac[num++].cnt=1;
    }
    for(int i=0;i<num;i++)//设置输出格式
    {
        if(i>0) cout<<"*";
        cout<<fac[i].x;
        if(fac[i].cnt>1) cout<<"^"<<fac[i].cnt;
    }
    return 0;
}

你可能感兴趣的:(算法学习)