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

本文解析了CodeForces竞赛中一道关于求最大公因数的题目,通过筛选质数并统计每个数的质因数来找出最多的共享质因数。使用C++实现算法,并包含了一个预处理质数的筛法。

本题链接: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 1

void init() {		// 利用筛法筛出10^5以内的素数
	notpm[1] = 1;	// 注意这句话,必须加上!否则会 Wrong answer on test 71
	for ( 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;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值