zoukankan      html  css  js  c++  java
  • poj2115——拓展欧几里德求模线性同余方程的最小正整数解

    poj2115——拓展欧几里德求模线性同余方程的最小正整数解

    C Looooops
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 18926   Accepted: 4973

    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
    题意:for(x=A;x!=B;x+=C,x%=1LL<<k) 求解结束时循环的次数
    思路:显然是求解方程(A+Cx)%n=B,(n=1<<k),变形得Cx%n=(B-A)%n,即转为模线性同余方程 Cx=(B-A)(mod n),扩展gcd解之即可
    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    
    using namespace std;
    
    const int maxn=1000100;
    const int INF=(1<<28);
    typedef long long ll;
    
    ll A,B,C,k;
    ll x,y;
    
    ll exgcd(ll a,ll b, ll &x, ll &y)
    {
        if(b==0){
            x=1;y=0;
            return a;
        }
        ll r=exgcd(b,a%b,x,y);
        ll t=y;
        y=x-a/b*y;
        x=t;
        return r;
    }
    
    bool mod_linear_equation(ll a,ll b,ll n)
    {
        ll d=exgcd(a,n,x,y);
        if(b%d) return false;
        x=x*(b/d)%n;
        x=(x%(n/d)+n/d)%(n/d);
        return true;
    }
    
    int main()
    {
        while(cin>>A>>B>>C>>k,A||B||C||k){
            if(mod_linear_equation(C,B-A,1LL<<k)) cout<<x<<endl;
            else cout<<"FOREVER"<<endl;
        }
        return 0;
    }
    View Code


    没有AC不了的题,只有不努力的ACMER!
  • 相关阅读:
    一周试用yii开发一个带各种该有功能的web程序(三)
    制作centos的U盘启动盘
    VMware下centos6.3minimal搭建网络环境
    [原]SQLite的学习系列之获取数据库版本
    Android Studio NDK 学习之接受Java传入的字符串
    [原]Ubuntu 14.04编译Android Kernel
    [原]运行编译好的Android模拟器
    [原]编译Android源码过程中遇到的问题
    [原]Android打包之Gradle打包
    [原]Android打包之跨平台打包
  • 原文地址:https://www.cnblogs.com/--560/p/4372794.html
Copyright © 2011-2022 走看看