sicily 1231. The Embarrassed Cryptography
Description
The young and very promising cryptographer Odd Even has implemented the security module of a large system with thousands of users, which is now in use in his company. The cryptographic keys are created from the product of two primes, and are believed to be secure because there is no known method for factoring such a product effectively. Input
The input consists of no more than 20 test cases. Each test case is a line with the integers 4 <= K <= 10100 and 2 <= L <= 106. K is the key itself, a product of two primes. L is the wanted minimum size of the factors in the key. The input set is terminated by a case where K = 0 and L = 0. Output
For each number K, if one of its factors are strictly less than the required L, your program should output "BAD p", where p is the smallest factor in K. Otherwise, it should output "GOOD". Cases should be separated by a line-break. Sample Input
143 10 143 20 667 20 667 30 2573 30 2573 40 0 0 Sample Output
GOOD BAD 11 GOOD BAD 23 GOOD BAD 31 |
分析:因为是 10^100,所以不能直接用内置数据类型,只能用大整数 判断是否能整除的一个方法是判断模值是否为 0,因为大整数求模比除法更简单,所以直接求模
#include <iostream> #include <string> using namespace std; bool is_mod(string num,int n) // 判断是否能够被整除 { int fac = 0; for(int i = 0; i < num.size(); i++) fac = (fac * 10 + (num[i] - '0')) % n; if(fac == 0) return true; return false; } int main(int argc, char const *argv[]) { int prime[1000001]; int primeNum = 0; for (int i = 2; i != 1000001; ++i) { prime[i] = 1; } for (int i = 2; i != 1000001; ++i) { // 筛选法求素数 if (prime[i] == 1) { prime[primeNum++] = i; // 将素数存到数组 for (int j = 2 * i; j < 1000001; j += i) prime[j] = 0; } } string num; int lowerBound; while (cin >> num) { bool flag = true; int factor = 0; cin >> lowerBound; if (num == "0" && lowerBound == 0) break; for (int i = 0; i != primeNum; ++i) { if (prime[i] < lowerBound) { // 找到最小的能被整除且在下界内部的素数 if (is_mod(num, prime[i])) { flag = false; factor = prime[i]; break; } } } if (flag) cout << "GOOD" << endl; else cout << "BAD " << factor << endl; } return 0; }