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

本文介绍了一种质因子分解算法,该算法通过获取素数表,使用埃氏筛选法找到所有质数,然后将输入的正整数分解为其质因子的乘积形式。文章详细解释了算法思路,并提供了完整的实现代码,包括如何存储质因子及其个数,以及如何按照特定格式输出分解结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

质因子分解

质因子分解即为将一个正整数分解为数个质因子相乘的形式。如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<iostream>
#include<math.h>
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无所畏惧的man

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值