zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    使用注解方式定义和配置aop
    javascript 相关小的知识点集合
    javascript ES3小测试
    js事件相关面试题
    前端工程师在面试过程中常遇到的知识点
    跨浏览器事件对象封装
    webstorm我用到的快捷键【不断更新】
    切图技巧分享—圆角背景色
    深入理解css中vertical-align属性
    photoshop CC智能切图
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409112.html
Copyright © 2011-2022 走看看