题目:
We have N chairs arranged in a circle, one of which is a throne.
Takahashi is initially sitting on the chair that is S chairs away from the throne in the clockwise direction. Now, he will repeat the move below.
Move: Go to the chair that is K chairs away from the chair he is currently sitting on in the clockwise direction.
After how many moves will he be sitting on the throne for the first time? If he is never going to sit on it, report -1 instead.
You are asked to solve T test cases.
1≤T≤100
2≤N≤1e9
1≤S<N
1≤K≤1e9
输入:
Input is given from Standard Input in the following format. The first line is in the format below:
T
Then, the following T lines represent T test cases. Each of these lines is in the format below:
N S K
输出:
For each test case, print the answer in its own line.
样例:
Sample Input 1
4
10 4 3
1000 11 2
998244353 897581057 595591169
10000 6 14
Sample Output 1
2
-1
249561088
3571
In the first test case, we have 10 chairs, and Takahashi is initially sitting on the chair that is 4 chairs away from the throne in the clockwise direction. He will be sitting on the throne after 2 moves of moving 3 chairs in the clockwise direction.
In the second test case, he will never sit on the throne, so we should print -1.
tag:
扩展欧几里得
题意:
有 N 个椅子围成一个圈,其中一个是王位。开始的时候,坐在离王位 S 的椅子上
他可以重复此操作:顺时针方向移动到距离自己k的椅子。
问,经过多少次移动,能第一次坐到王位。如果不可能,输出 -1。
思路:
设移动x次后,到达王座,此时一共转了y圈
要使得最后到达王座 那么有 (kx+s)%n=0,即求最小正整数解x
kx + ny = -s
由拓展欧几里得 d=exgcd(k,n,x,y)
如果 s%d!=0则无解 否则可得 x= (-xs/d%t+t)%t其中t=n/d
代码
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y){
if(b==0){
x=1,y=0;
return a;
}
ll d=exgcd(b,a%b,y,x);
y=y-(a/b)*x;
return d;
}
int main()
{
int t;
cin >> t;
while(t--){
ll n,s,k;
cin >> n >> s >> k;
ll x,y;
ll d=exgcd(k,n,x,y);
if(s%d){
cout << -1 << endl;
}
else{
ll t=n/d;
cout << (-x*s/d%t+t)%t << endl;
}
}
return 0;
}