码迷,mamicode.com
首页 > 其他好文 > 详细

HDU - 4135 Co-prime

时间:2016-05-07 11:14:33      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

/*

我觉得这道题最给力的地方是帮我想清楚了一件事,就是如何将一个数字n中的因子全部分离出来。

1.首先筛选出sqrt(n)中所有的素数

2.随后用得到的素数一个个去试除n,当n%prime==0时,就除尽所有的素数

3.最后如果得到的n大于1,说明最后剩余的也是一个素数,应该被加入素因子集合中

可以考虑取21的所有素因子的过程

*/

1.题面

http://acm.hdu.edu.cn/showproblem.php?pid=4135

2.题意

给你区间[a,b],和一个数n,求[a,b]之间和n互素的数字的个数。

3.思路

容斥原理的使用

4.代码

/*****************************************************************
    > File Name: Cpp_Acm.cpp
    > Author: Uncle_Sugar
    > Mail: uncle_sugar@qq.com
    > Created Time: 2016年05月05日 星期四 21时25分08秒
*****************************************************************/
# include <cstdio>
# include <cstring>
# include <cctype>
# include <cmath>
# include <cstdlib>
# include <climits>
# include <iostream>
# include <iomanip>
# include <set>
# include <map>
# include <vector>
# include <stack>
# include <queue>
# include <algorithm>
using namespace std;

const int debug = 1;
const int size  = 100000 + 10; 
const int INF = INT_MAX>>1;
typedef long long ll;

bool isprime[size];
ll prime[size];
int prim_size;
void PrimeTable(){
	fill(isprime,isprime+size,true);
	prim_size = 0;
	isprime[0] = isprime[1] = false;
	for (int i=2;i<size;i++){
		if (isprime[i])
			prime[prim_size++] = i;
		for (int j=0;j<prim_size&&prime[j]*i<size;j++){
			isprime[i*prime[j]] = false;
			if (i%prime[j]==0)
				break;
		}
	}
}

ll factor[size];
int fact_size = 0;
void getfactor(ll n){
	fact_size = 0;
	//# if (debug)	cout << "prim_size = " << prim_size << endl;
	int lmt = (int)sqrt(n)+1;
	for (int i=0;i<prim_size&&prime[i]<=lmt;i++){
		//# if (debug)	cout << "i = " << i << endl;
		if (n%prime[i]==0){
			while (n%prime[i]==0){
				n /= prime[i];
				//# if (debug)	cout << "n = " << n << endl;
			}
			factor[fact_size++] = prime[i];
		}
		if (n==1)
			break;
	}
	if (n>1)
		factor[fact_size++] = n;
	//# if (debug){
		//# cout << "factor\n";
		//# for (int i=0;i<fact_size;i++){
			//# cout << factor[i] << endl;
		//# }
	//# }
}

ll coprime[size];
int coprim_size;
ll getcoprime(ll n){
	coprime[0] = 1;
	coprim_size = 1;
	ll ans = 0;
	for (int i=0;i<fact_size;i++){
		int t = coprim_size;
		for (int j=0;j<coprim_size;j++){
			coprime[t++] = coprime[j]*factor[i]*(-1);
		}
		coprim_size = t;
	}
	for (int i=0;i<coprim_size;i++){
		ans += n/coprime[i];
	}
	return ans;
}
int main()
{
	std::ios::sync_with_stdio(false);cin.tie(0);
	int i,j;
	int T,ncase=0;
	cin >> T;
	PrimeTable();
	while (T--){
		ll a,b,c;
		cin >> a >> b >> c;
		getfactor(c);
		cout << "Case #" << ++ncase << ": "<< getcoprime(b) - getcoprime(a-1) << endl;
	}
	return 0;
}


HDU - 4135 Co-prime

标签:

原文地址:http://blog.csdn.net/sinat_29278271/article/details/51332482

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!