There is a computer, which has two memory cells (let us denote these
cells by the letters a and b ). Each cell (variable) stores some
integer at any time. The computer can execute only two instructions
a+=b and b+=a . The rst instruction increases the value of the
variable a by the value stored in the variable b . The second one,
respectively, increases the value of b by the value a . A program for
this computer consists of a sequence (possible empty) of such
instructions. The instructions are executed in the appropriate order.
Your task is to determine whether the given value S can be obtained in
some cell after executing some program. Input The input le contains
several test cases, each of them as described below. The input
contains three integers: the initial value of the variable a , the
initial value of the variable b and the required value S (0 a;b;S
10 18 ). SampleOutput For each test case, write to the outputYES '
NO ’ otherwise on a line by itself.
if the required value can be obtained as a result of some program
execution, or
可以发现,对于两个系数的来回相加其实就是逆过来的辗转相减。因为初始情况(1,1)的gcd是1,所以来回相加之后只需要保证系数互质。
可以先用扩展欧几里得求出一组x,y使得ax+by=s,然后推出所有非负整数解进行验证。
#include<cstdio>
#include<cstring>
#define LL long long
LL gcd(LL a,LL b,LL &x,LL &y)
{
if (!b)
{
x=1;
y=0;
return a;
}
LL ret=gcd(b,a%b,y,x);
y-=a/b*x;
return ret;
}
int main()
{
LL a,b,s,d,x,y,t1,t2,A,B;
bool flag;
while (scanf("%lld%lld%lld",&a,&b,&s)==3)
{
if (a==0&&b==0)
{
if (s==0) printf("YES\n");
else printf("NO\n");
continue;
}
if (a==0)
{
if (s%b==0) printf("YES\n");
else printf("NO\n");
continue;
}
if (b==0)
{
if (s%a==0) printf("YES\n");
else printf("NO\n");
continue;
}
d=gcd(a,b,x,y);
if (s%d)
{
printf("NO\n");
continue;
}
A=a/d;
B=b/d;
x=(x%B)*(s/d%B)%B;
x=(x%B+B)%B;
y=(s-a*x)/b;
flag=0;
while (y>=0)
{
if (gcd(x,y,t1,t2)==1)
{
flag=1;
break;
}
x+=B;
y-=A;
}
if (flag) printf("YES\n");
else printf("NO\n");
}
}