首页 > 技术文章 > poj 2115 C Looooops

-citywall123 2019-04-12 09:46 原文

http://poj.org/problem?id=2115

C Looooops
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 34291   Accepted: 9996

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

题意:求解最小的x使得 a + c*x = b (mod 2

k

)。变形,用扩展欧几里得解线性同余方程即可
变形: a+cx=b%(2^k) --> a%2^k+cx%2^k=b%2^k --> cx%2^k=(b-a)%2^k
假设一个整数y;
因为 cx%2^k=(cx+y*2^k)%2^k;
所以 cx%2^k=(cx+y*2^k)%2^k=(b-a)%2^k --> c*x+2

k

*y=(b-a)
最后判断这个线性同余方程是否有解-----线性同余方程有解的充分必要条件是(b-a)%gcd(c,2

k

)==0
无解输出 FOREVER

PS:POJ对数学函数的数据类型要求特别严格,不符合函数数据类型的都会报错。
给出几个正确的类型:
pow(double,int) sqrt(double)
#include<iostream>
#include<string.h>
#include<math.h>
#define max 0x3f3f3f3f
#define ll long long
#define mod 1000000007
using namespace std;
ll x,y,r,s;
void exgcd(ll a, ll b, ll &x, ll &y)    //拓展欧几里得算法
{
    if(!b) 
        x = 1, y = 0;
    else
    {
        exgcd(b, a % b, y, x);
        y -= x * (a / b);
    }
}

ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}
void TY(ll a,ll b,ll c)
{
    r=gcd(a,b);
    s=b/r;
    exgcd(a,b,x,y);//得到x0
    x=x*c/r;  //得到x1
    x=(x%s+s)%s;  //得到最小正整数解
}
int main()
{
    ll a,b,c;
    int k;
    while(scanf("%lld%lld%lld%d",&a,&b,&c,&k))
    {
        if(a==0&&b==0&&c==0&&k==0)
            break;
        else
        {
            if((b-a)%gcd(c,pow(2.0,k))!=0)
                printf("FOREVER\n");
            else
            {
                TY(c,pow(2.0,k),b-a);
                printf("%lld\n",x);
            }
        }
    }
    return 0;
}

 

推荐阅读