uva583 Prime Factors

本文介绍了一种质因数分解算法的C++实现方法,通过预先生成一定范围内的质数列表,然后利用这些质数对输入的整数进行分解,得到其所有质因数的乘积形式。

Sample Input
-190
-191
-192
-193
-194
195
196
197
198
199
200
0
Sample Output
-190 = -1 x 2 x 5 x 19
-191 = -1 x 191
-192 = -1 x 2 x 2 x 2 x 2 x 2 x 2 x 3
-193 = -1 x 193
-194 = -1 x 2 x 97
195 = 3 x 5 x 13
196 = 2 x 2 x 7 x 7
197 = 197
198 = 2 x 3 x 3 x 11
199 = 199
200 = 2 x 2 x 2 x 5 x 5

#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
using namespace std;
int c[1<<17];int k=0;
int judge(){

    c[k++]=2;
    c[k++]=3;
    for(int j=4;j<(1<<17);j++){
        int flag=1;
        for(int i=2;i<=sqrt(j)+1;i++){
            if(j%i==0){
                flag=0;
                break;
            }
        }
        if(flag)
            c[k++]=j;
    }
}
int main()
{
    int n;
    judge();//runtime了老长时间竟然是因为把这个函数放循环内了……
    while(cin>>n,n){
        cout<<n<<" =";
        int m=n;
        if(n<0){
            cout<<" -1 x";
            n=-1*n;
        }
        int flag=0,first=0;
        for(int i=0;c[i]<n&&i<k;i++){//c[i]<n,一定是n,跟随着n的变化来调整循环量,否则会超时
            while(n%c[i]==0){
                if(first++){
                    cout<<" ";
                }
                if(flag++)
                    cout<<"x "<<c[i];
                else
                    cout<<" "<<c[i];
                n/=c[i];
            }
        }
        if(n==1&&flag)//如果进循环了
        cout<<endl;
        else if(flag==0)
            cout<<" "<<n<<endl;
        else
            cout<<" x "<<n<<endl;


    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值