[欧拉函数][gcd]Same GCDs CF1295D

16 篇文章 0 订阅

You are given two integers a and m. Calculate the number of integers x such that 0≤x<m and gcd(a,m)=gcd(a+x,m).

Note: gcd(a,b) is the greatest common divisor of a and b.

Input

The first line contains the single integer T (1≤T≤50) — the number of test cases.

Next T lines contain test cases — one per line. Each line contains two integers a and m (1≤a<m≤10^10).

Output

Print T integers — one per test case. For each test case print the number of appropriate x-s.

Sample 1

InputOutput
3
4 9
5 10
42 9999999967
6
1
9999999966

Note

In the first test case appropriate x-s are [0, 1, 3, 4, 6, 7].

In the second test case the only appropriate x is 0.

题意: 寻找有多少个x满足0≤x<m且gcd(a, m) == gcd(a+x, m)。

分析: 涉及到gcd所以要往gcd(a, b) == gcd(a%b, b)这个公式上凑。考虑将x分段,当0<=x<=m-a时就是k∈[a, m]时gcd(a, m) == gcd(k, m)的个数。当m-a+1<=x<=m-1时就是k∈[m+1, m+a-1]时gcd(a, m) == gcd(k, m)的个数,这里的gcd(k, m)用公式变形一下就是gcd(k%m, m),所以就是求k∈[1, a-1]时gcd(a, m) == gcd(k, m)的个数。两种情况综合一下就是求k∈[1, m]时gcd(a, m) == gcd(k, m)的个数,对[1, m]的每个数都除以gcd(a, m),显然有很多数是没法整除的,说明这些数中不含gcd(a, m)这个因数,可以把这些数直接扔掉,最后只剩下m/gcd(a, m)个能被整除的数,除完以后这些数就是[1, m/gcd(a, m)]区间内的数字,而这些数中与m/gcd(a, m)互质的数就是原来与m的gcd为gcd(a, m)的数,因此答案就是m/gcd(a, m)的欧拉函数值。

具体代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define int long long
using namespace std;

int phi(int x)
{
	int ans = x;
	for(int i = 2; i*i <= x; i++)
	{
		if(x%i == 0)
		{
			ans = ans/i*(i-1);
			while(x%i == 0)
				x /= i;
		}
	}
	if(x > 1) ans = ans/x*(x-1);
	return ans;
}

signed main()
{
	int T;
	cin >> T;
	while(T--)
	{
		int a, b;
		scanf("%lld%lld", &a, &b);
		printf("%lld\n", phi(b/__gcd(a, b)));
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值