Uva 10392 - Factoring Large Numbers
Problem F:
Factoring Large Numbers
One of the central ideas behind much cryptography is that factoring large numbers is computationally intensive. In this context one might use a 100 digit number that was a product of two 50 digit prime numbers. Even with the fastest projected computers this factorization will take hundreds of years.
You don't have those computers available, but if you are clever you can still factor fairly large numbers.
Input
The input will be a sequence of integer values, one per line, terminated by a negative number. The numbers will fit in gcc's long long int
datatype. You may assume that there will be at most one factor more than 1000000.
Output
Each positive number from the input must be factored and all factors (other than 1) printed out. The factors must be printed in ascending order with 4 leading spaces preceding a left justified number, and followed by a single blank line.
Sample Input
90 1234567891 18991325453139 12745267386521023 -1
Sample Output
2 3 3 5 1234567891 3 3 13 179 271 1381 2423 30971 411522630413
#include<stdio.h> #include<string.h> #define MAXN 1000000 int prime[MAXN]; int flag[MAXN]; is_prime() { /* 筛不超过1000000的素数(注意题目的提示 ; You may assume that there will be at most one factor more than 1000000. ) 存储到prime数组中,并返回素数的个数 */ int i, j, n = 0; memset(flag, 0, sizeof(flag)); for(i=2; i<MAXN; ++i) { if(!flag[i]) { prime[n++] = i; flag[i] = 1; for(j=i+i; j<MAXN; j+=i) flag[j] = 1; } } return n; } int main() { int term, track, i, j; long long n; term = is_prime(); while(scanf("%lld", &n) != EOF && n >= 0) { if(n == 0 || n == 1) {//处理 n = 1 和 n = 0 特殊情况 printf(" 1\n\n"); continue; } for(track=i=0; n != 1 && n != 0 && i<term; ++i) { while(n%prime[i] == 0) { flag[track++] = prime[i]; n /= prime[i]; } } for(i=0; i<track; ++i) printf(" %d\n", flag[i]); if(n != 1) printf(" %lld\n\n", n); else printf("\n"); } return 0; }
解题思路:
刚开始肯定会觉得难求(这个看样例就知道了)但再回去看一遍题目的时候,就发现了那句很重要的话
You may assume that there will be at most one factor more than 1000000.
这说明最大的因子(素数)并不会超过10^6次方
![物役记](https://s2.ax1x.com/2019/05/26/VE5YD0.jpg)
更多内容请关注个人微信公众号 物役记 (微信号:materialchains)