Problem F: Factoring Large Numbers
One of the central ideas behind much cryptography is that factoringlarge numbers is computationally intensive. In this context one mightuse a 100 digit number that was a product of two 50 digit primenumbers. Even with the fastest projected computers this factorizationwill take hundreds of years.
You don't have those computers available, but if you are clever youcan 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'slong long int
datatype.You may assume that there will beat 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 ascendingorder with 4 leading spaces preceding a left justified number, andfollowed 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
这题大意就是求一个数的质因数,由于这题的质因子的数据量就只到1,000,000所以先用了筛法,将1,000,000以内的质数都找出来,然后将给定的去余这些质数,将能整除的质数输出,要注意的就是给定的数是要用long long来做。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int N = 10000000;
bool is_prime[N];
int prime[N];
int prime_number;
long long number;
int main() {
while (cin >> number) {
if (number < 0)
break;
memset(is_prime,true,sizeof(is_prime));
memset(prime,0,sizeof(prime));
prime_number = 0;
is_prime[0] = false;
is_prime[1] = false;
for (int i = 2; i <= N && i <= (int)sqrt(number); i++) {
if (is_prime[i]) {
prime[prime_number] = i;
while (prime[prime_number] && number % prime[prime_number] == 0) {
cout << " " << prime[prime_number] << endl;
number /= prime[prime_number];
}
prime_number++;
}
for (int j = 0; j < prime_number && i*prime[j] <= N && i*prime[j] <= (int)sqrt(number); j++) {
is_prime[i*prime[j]] = false;
if (prime[j] && i % prime[j] == 0)
break;
}
}
if (number > 1)
cout << " " << number << endl;
cout << endl;
}
return 0;
}