uva583 Prime Factors

来源:互联网 发布:java mongodb 连接池 编辑:程序博客网 时间:2024/06/07 01:35

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;}
原创粉丝点击