• 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;
    }

  • 相关阅读:
    极光推送的设备唯一性标识 RegistrationID
    排行榜算法设计实现比较 排序树 平衡二叉树
    UCloud首尔机房整体热迁移是这样炼成的
    from appium import webdriver 使用python爬虫,批量爬取抖音app视频(requests+Fiddler+appium)
    客户续费模型 逻辑回归 分类器 AdaBoost
    推举算法 AdaBoost 哥德尔奖 Godel Prize
    基于 redis 的分布式锁实现 Distributed locks with Redis debug 排查错误
    Django’s cache framework
    随机森林算法预测法官判决
    时间特征正弦化
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409112.html
Copyright © 2020-2023  润新知