C Looooops
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 25950 Accepted: 7352
Description
A Compiler Mystery: We are given a C-language style for loop of type
for (variable = A; variable != B; variable += C)
statement;
I.e., a loop which starts by setting variable to value A and while variable is not equal to B, repeats statement followed by increasing the variable by C. We want to know how many times does the statement get executed for particular values of A, B and C, assuming that all arithmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2k) modulo 2k.
Input
The input consists of several instances. Each instance is described by a single line with four integers A, B, C, k separated by a single space. The integer k (1 <= k <= 32) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, C < 2k) are the parameters of the loop.
The input is finished by a line containing four zeros.
Output
The output consists of several lines corresponding to the instances on the input. The i-th line contains either the number of executions of the statement in the i-th instance (a single integer number) or the word FOREVER if the loop does not terminate.
Sample Input
3 3 2 16
3 7 2 16
7 3 2 16
3 4 2 16
0 0 0 0
Sample Output
0
2
32766
FOREVER
题目大意:解cx =b-a mod 2^k,求x的最小非负整数解
解题思路:单变元模线性方程,正好验证一下模板,ans稍微修改一下,只保留第一个就好,不然会MLE
#include#includeusingnamespacestd;
typedeflonglong LL;
//ax+by=gcd(a,b)
LL extend_gcd(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x=1;y=0;
return a;
}else
{
LL r=extend_gcd(b,a%b,y,x);
y-=x*(a/b);
return r;
}
}
//ax≡b(mod n)//ax+ny=b//输出所有[0,n)中的解vector line_mod_equation(LL a,LL b,LL n)
{
LL x,y;
//ax+ny=gcd(a,n)=d
LL d=extend_gcd(a,n,x,y);
vector ans;
ans.clear();
if(b%d==0)
{
/*******************
x*a+n*y=gcd(a,n)=d;
x0=(x*b/d);
y0=(y*b/d);
x0*a+n*y0=b;
x0*a+n*y0=x1*a+n*y1;
(x0-x1)*a=(y1-y0)*n;
(x0-x1)*a/d=(y1-y0)*n/d;
(x0-x1)=kk*(n/d);
x1=x0+k*(n/d);
x0=(x0%(n/d)+(n/d))%(n/d);//最小非负整数解
********************/
x*=(b/d);
x=(x%(n/d)+(n/d))%(n/d);
ans.push_back(x);
//for(LL i=1;i//ans.push_back((ans[0]+i*n/d)%n);
}
return ans;
}
//(a+cx)mod 2^k=b;//cx =b-a mod 2^k;int main()
{
LL a,b,c,k;
while(cin>>a>>b>>c>>k)
{
if(a==0&&b==0&&c==0&&k==0) break;
vector ans;
ans.clear();
ans=line_mod_equation(c,b-a,1LL<vector::iterator it;
if(ans.empty()) {cout<<"FOREVER"<continue;}
cout<0]<return 0;
}