• C Looooops(扩展欧几里得)题解


    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

    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 < 2 k) 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


    思路:

    和之前做的差不多:青蛙

    发现模线性方程不会转化orz,贴一下:模线性方程

    模线性方程转化:当 a*xb mod m时,可以转化为 a*x+m*y=b求解x,y 

    那么我们先来列出原题模线性方程:C*t+A B mod(2^k)  ==>   C*t ≡ B-A  mod(2^k) ==>  C*t + (2^k)*y B-

    代码:

    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<queue>
    #include<cmath>
    #include<string>
    #include<map>
    #include<stack> 
    #include<set>
    #include<vector>
    #include<iostream>
    #include<algorithm>
    #define INF 0x3f3f3f3f
    #define ll long long
    const int N=2000000000;
    const int MAX=2100000000;
    const int MOD=1000; 
    using namespace std;
    ll ex_gcd(ll a,ll b,ll &x,ll &y){
    	ll d,t;
    	if(b==0){
    		x=1;
    		y=0;
    		return a;
    	}
    	d=ex_gcd(b,a%b,x,y);
    	t=x-a/b*y;
    	x=y;
    	y=t;
    	return d;
    }
    int main(){
    	ll a,b,c,k,A,B,C,d,x,y;
    	while(~scanf("%lld%lld%lld%lld",&A,&B,&C,&k) && A+B+C+k){
    		a=C;
    		b=(ll)1<<k;
    		c=B-A;
    		d=ex_gcd(a,b,x,y);
    		if(c%d!=0){
    			printf("FOREVER
    ");
    		}
    		else{
    			x=x*c/d;
    			ll k=b/d;
    			x=(x%k+k)%k;
    			printf("%lld
    ",x);
    		}
    	} 
    	return 0;
    }

  • 相关阅读:
    Using PL/SQL APIs as Web Services
    1.Cocos2dx 3.2中vector,ValueMap,Touch触摸时间的使用.iconv字符编解码
    我对贝叶斯分类器的理解
    VB.NET的前世今生
    《转》PyQt4 精彩实例分析* 实例2 标准对话框的使用
    网络流合集:bzoj1433,1934,1854 题解
    Android 下拉刷新上拉载入 多种应用场景 超级大放送(上)
    Nginx 笔记与总结(15)nginx 实现反向代理 ( nginx + apache 动静分离)
    深入浅出之数据分析四步曲
    深入浅出之数据分析四步曲
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409112.html
Copyright © 2020-2023  润新知