题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=100&page=show_problem&problem=1333
题目意思为,输入一个大数n(g++下为long long),输出他的所有质因数。
因为题中有一句:
You may assume that there will be at most one factor more than 1000000.
意思是最多有一个因子大于1000000,那么说明其他因子均在1-1000000之间,于是遍历1000000,对每个数,循环得去除n,直到不能整除,则换下一个因子。
这里不用去算出1000000以内的所有质数,因为循环过程中,如果因子是非质数,比如:4,那么在除以2的阶段,早就把4这个因子除掉了,当前的n肯定不能被4整除。
循环到最后,如果n为1了,说明没有大于1000000的因子,退出循环结束,否则循环肯定遍历完所有因子,此时若n不为1,还要输出n。
----------------------------------------------------------------
另外记一下,如何判断一个数为素数:
判断一个整数m是否为素数只需被2~根号m之间的每个数去除就可以了。只要整除,则不是素数。
-------------------------------------------------
代码:
#include<iostream> #include<stdio.h> #include<vector> #include<algorithm> #include<fstream> using namespace std; int main() { //ifstream cin("in"); long long n; while(cin>>n) { if(n<0) break; for(long long x = 2; x <= 1000000; x++) { while(n % x == 0) { cout<<" "<<x<<endl; n /= x; } if(n == 1) break; } if(n != 1) cout<<" "<<n<<endl; cout<<endl; } }