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
题意:属于求解模线性方程的题,cx-y*2k=b-a
AC代码:
#include<iostream>
#include<string.h>
#include<string>
#include<cstdio>
#define N 11
using namespace std;
typedef long long L;
L d;
void gcd(L a,L b,L &x1,L &y1)
{
if(!b) {x1=1;y1=0;d=a;}
else
{
gcd(b,a%b,x1,y1);
int temp=x1;
x1=y1;
y1=temp-a/b*x1;
}
}
int main()
{
L a,b,c,k;
while(~scanf("%lld%lld%lld%lld",&a,&b,&c,&k),a,b,c,k)
{
L a1=c;
L b1=(L)1<<k;//以2为底的幂运算可以由位运算来解决
L c1=b-a;
L x1,y1;
gcd(a1,b1,x1,y1);
L r=b1/d;
if(c1%d) printf("FOREVER\n");
else printf("%lld\n",(c1/d*x1%r+r)%r);
}return 0;
}
本文介绍了一种计算特定C语言循环执行次数的方法,通过解析循环参数与位运算技巧,利用模线性方程求解执行次数,适用于k位无符号整数计算。
5万+

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



