Description
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 < 2k) modulo 2k.
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.
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
这道题相当于求ax=b(mod n)的最小解(对于这题,a=C,b=B-A,n=2k),使用扩展欧几里得算法可以得到解,下面是程序:
#include<stdio.h>
#include<iostream>
#define ll long long
using namespace std;
ll read(){
ll s=0;
char c=getchar();
while(c<'0'||c>'9'){
c=getchar();
}
while(c>='0'&&c<='9'){
s*=10;
s+=c-'0';
c=getchar();
}
return s;
}
bool in(ll &a,ll &b,ll &c,ll &k){
a=read();
b=read();
c=read();
k=read();
return a|b|c|k;
}
ll gcd(ll a,ll b,ll &x,ll &y){
if(!b){
x=1;
y=0;
return a;
}
ll d=gcd(b,a%b,x,y);
ll tp=x;
x=y;
y=tp-a/b*y;
return d;
}
void out(ll x){
if(x>9){
out(x/10);
}
putchar(x%10+'0');
}
int main(){
ll a,b,c,k;
while(in(a,b,c,k)){
ll x,y,tp=b-a,n=1ll<<k;
ll d=gcd(c,n,x,y);
if(tp%d){
printf("FOREVER\n");
}
else{
x=(x*(tp/d))%n;
out((x%(n/d)+n/d)%(n/d));
putchar('\n');
}
}
return 0;
}

博客介绍了如何运用扩展欧几里得算法解决POJ 2115题目——C Looooops(CTU Open 2004)。该问题要求找到最小解ax=b (mod n),其中a=C, b=B-A, n=2k。通过算法实现,可以高效求解此类模线性方程。"
110863587,10296763,Excel中文本型数字与数值型数字的转换,"['Excel技巧', '数据处理', '文本格式', '数值格式']
545

被折叠的 条评论
为什么被折叠?



