1059. Prime Factors (25)

本文介绍了一个使用C++实现的质因数分解算法。该算法能够将输入的整数分解为其所有质因数的乘积形式,并通过优化判断过程提高了效率。文中详细展示了如何检查一个数是否为质数,并利用循环逐步分解合数。

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

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>

#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <set>

using namespace std;

bool isp(int a)
{
    if(a==1)
        return 0;

    for(int i=2;i<=(int)sqrt(a);i++)
    {
        if(a%i==0)
            return 0;
    }
    return 1;
}

vector<long long> v;
queue<long long> q;

int main()
{
  //  freopen("in.txt","r" ,stdin);

    long long N;
    scanf("%lld",&N);
    printf("%lld=",N);

    if(N==1)
    {
        printf("1");
        return 0;
    }
    while(N!=1)
    {
        for(int i=2;;i++)
        {
            if(isp(i) && N%i==0)
            {
                q.push(i);
                N/=i;
                break;
            }
        }
    }

    int flag=0;
    long long k=0;
    while(!q.empty())
    {
        long long t=q.front();
        q.pop();

        if(t==q.front())
        {
            k++;
        }
        else
        {
            if(k==0)
            {
                if(flag==0)
                    flag=1;
                else
                    printf("*");

                printf("%lld",t);
            }
            else
            {
                if(flag==0)
                    flag=1;
                else
                    printf("*");

                printf("%lld^%lld",t,k+1);

                k=0;
            }
        }

    }






    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值