链接:http://acm.hust.edu.cn/vjudge/problem/21464/origin
题目:A Compiler Mystery: We are given a C-language style for loop of type
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 < 2 k) modulo 2 k.
题意:for(int i=a;i!=b;i+=c) sec;这是一个循环,如果i的值超过了存储上限会对存储上限取模,在再进行计算,问sec语句执行几次。
分析:一样的扩展欧几里得问题,假设上限为k转化后为求cx+ky=b-a的x的一个特解。带入模板可求。
题解:
题目: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 < 2 k) modulo 2 k.
题意:for(int i=a;i!=b;i+=c) sec;这是一个循环,如果i的值超过了存储上限会对存储上限取模,在再进行计算,问sec语句执行几次。
分析:一样的扩展欧几里得问题,假设上限为k转化后为求cx+ky=b-a的x的一个特解。带入模板可求。
题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define pii pair<int,int>
#define lowbit(x) x&(-x)
using namespace std;
#define maxi 0x3f3f3f3f
#define MAX 100010
ll gcd(ll a, ll b)//小心b为零的情况,保证输入的时候b不为零
{
rt (a%b) ? gcd(b, a%b) : b;
}
ll exgcd(ll a, ll b, ll &x, ll &y)//小心b为零的情况,保证输入的时候b不为零
{
if (b == 0)
{
x = 1;
y = 0;
rt a;
}
ll d = exgcd(b, a%b, x, y);
ll temp = x;
x = y;
y = temp - a / b*y;
rt d;
}
ll quickpow(ll x, ll n)
{
ll t = x;
ll ans = 1;
while (n)
{
if (n & 1)ans *= t;
n /= 2;
t = t*t;
}
rt ans;
}
int main()
{
//fr;
detie;
ll a, b, c, k;
while (cin >> a >> b >> c >> k)
{
if (a == 0 && b == 0 && c == 0 && k == 0)
break;
k = quickpow(2, k);
ll m = gcd(c, k);//神特么c可能为零,这特么的顺序还很重要。。。
if ((b - a) % m != 0)
{
cout << "FOREVER" << endl;
continue;
}
ll x, y;
exgcd(c, k, x, y);
x = (b - a) / m*x;
x = (x % (k / m) + k / m) % (k / m);
cout << x << endl;
}
rt 0;
}