Codeforces 757B Bash's Big Day 【数论】

来源:互联网 发布:冬不拉教程软件 编辑:程序博客网 时间:2024/05/29 18:37

本题链接:http://codeforces.com/contest/757/problem/B

题目大意:有 n 个数,问有不为1的公因数的数最多是几个。


思路:

将这 n 个数所有的因数(如果是质数,就是它本身。如果不是质数,就是除1以外的所有因数)都统计在一个数组 times[] 中, times[i] == y 表示这个数(i)是n个数中 y个数的因数,最后统计哪个因数出现的次数多就可以了。

剪枝是:用一个预处理将10^5以内的质数都计算出来,在进行计算会方便的多。

还有,小心被 hack QAQ

#include <cstdio>#include <iostream>#include <algorithm>using namespace std;const int size = 1e5+5;int n;int a[size];//  notpm[i] == 0 表示 i 为素数, notpm[i] == 1 表示 i 不为素数//  pm[i] 表示从 2 开始的第 i 个素数int notpm[size], pm[size];int curs = 0;// Test: #71,// 10 // 1 1 1 1 1 1 1 1 1 1void init() {// 利用筛法筛出10^5以内的素数notpm[1] = 1;// 注意这句话,必须加上!否则会 Wrong answer on test 71for ( int i = 2; i <= 1e5; i ++ ) {if(!notpm[i]) {pm[++ curs] = i;} else {for ( int j = i*2; j <= 1e5; j += i ) {notpm[j] = 1;}}}}int times[size];int mx(int a, int b) { return a>b?a:b; }int main() {scanf("%d", &n);for ( int i = 0; i < n; i++ ) scanf("%d", &a[i]);init();for ( int i = 0; i < n; i++ ) {int temp = a[i];for ( int j = 1; pm[j]*pm[j] <= temp; j ++ ) {if(temp%pm[j] == 0) {// 寻找 temp 最小的质因子为最终times[pm[j]] ++;while( temp%pm[j] == 0 ) temp /= pm[j];}}if(!notpm[temp]) times[temp] ++;// 对于素数来说,最大的质因子是他自己}int ans = 1;for ( int i = 0; i < size; i++ ) {ans = mx(ans, times[i]);}printf("%d\n", ans);return 0;}


1 0