寒假集训_专题四题解_K - Co-prime

题目

Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Input
The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 10 15) and (1 <=N <= 10 9).
Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.
Sample Input
2
1 10 2
3 15 5
Sample Output
Case #1: 5
Case #2: 10

Hint
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.

题目大意

给你三个数a、b、n求[a,b]中于n互质的数的个数

题解

1.首先可以转化题目位求与n不互质的数的个数,再用总数减去即可
2.对于[a,b]可用前缀和的思想,分别求[1,a-1]与[1,b]中与n不互质的数的个数
3.[1,s]中与n不互质的数的个数可以根据容斥原理得出

代码

#include <iostream>
using namespace std;
const int N = 1e6+10;
typedef long long LL;
int cnt = 0, primes[N],primes_now[N],cnt_now;
bool st[N],primes_st[N];
LL a,b,n;
void get_primes()
{
	st[1] = true;
	for(int i = 2; i*i <= N; i ++)
	if(!st[i])
	{
		for(int j = i*2; j<=N/j; j += i)
		st[j] = true;
		primes[cnt++] = i;
	}
 } 
 LL dfs(int k, LL s,LL step, LL &ans,int now)
 //k:还需选几位 s:从1到s的和 step:所有被选中的primes的积 ans:返回值 now:从第几位开始选 
 {
 	if(s == 0)return 0;
 	if(k==0)ans += s/step;
	else 
 	for(int i = now; i < cnt_now; i ++)
 	if(!primes_st[i])
 	{
 		primes_st[i] = true;
 		dfs(k-1,s,step*primes_now[i],ans,i+1);
 		primes_st[i] = false;
	}
	return ans;
 }
 int main()
 {
 	get_primes();
 	int T;scanf("%d",&T);
	for(int i = 1; i <= T; i ++)
	{
		cin >> a >> b >> n;
		cnt_now = 0;
		for(int j = 0; j < cnt; j ++)
		{
			if(n==1)break;
			if(n%primes[j] == 0)
			{
				primes_now[cnt_now++] = primes[j];
				while(n%primes[j] == 0)n/=primes[j];
			}
		}
		if(n != 1)primes_now[cnt_now++] = n;
		LL ans = b-a+1;
		for(int j = 1; j <= cnt_now; j ++)
		{
			LL t1 = 0, t2 = 0;
			if(j&1)ans-=dfs(j,b,1,t1,0)-dfs(j,a-1,1,t2,0);
			else ans += dfs(j,b,1,t1,0)-dfs(j,a-1,1,t2,0);
		}
		printf("Case #%d: %lld\n",i,ans);
	}
	return 0;
 }

Be careful:

注意dfs中的now

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值