zoukankan      html  css  js  c++  java
  • POJ 2115 ( 中国剩余定理 )

    C Looooops
    Time Limit: 1000MS Memory Limit: 65536K
    Total Submissions: 17625 Accepted: 4563

    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

    题意:变量初始为A,然后每次加C,问需要几步才能等于 B。不过每次都要对 2的k次方 取模。 即 A+ xC= B( mod 1<<k) 

    整理得:Cx  = B-A ( mod 1<<k)----->Cx + (1<<k) y = B-A----->aX + bY = c   (  其中a = C,   b = 1<<k, c = B-A)。

      然后再利用拓展欧几里得求最小正整数x即可。


    #include<stdio.h>
    #include<math.h>
    #define LL long long
    LL a, b, c ,k, x, y;
    
    int ext_gcd(LL a, LL b, LL &x, LL &y)
    {
        if(b==0) {
            x=1;
            y=0;
          return a;
        }
        LL u = ext_gcd(b, a%b, x ,y);
        LL t = x;
           x = y;
           y = t-a/b*y;
        return u;
    }
    
    int main()
    {
        while(~scanf("%lld%lld%lld%lld", &a, &b, &c, &k))
        {
            if(a==0 && b==0 && c==0 && k==0)
                  break;
            LL C = b-a, A = c, B = (LL)1<<k;
            LL d = ext_gcd(A, B, x, y);
            if(C%d!=0)
            {
                printf("FOREVER
    ");
            }
            else
            {
                x = x*C/d;
                B = B/d;
                x = (x%B+B)%B;
                printf("%lld
    ", x);
            }
        }
        return 0;
    }
    


    每天训练发现我比别人做的好慢,但是理解的更深刻,如果一开始学一个新知识点就搜模板,那么这样的人是走不远的,毕业之后带走的只有思维,什么荣誉,奖杯都已经不重要了。
  • 相关阅读:
    Apache Commons Configuration的应用
    JAVA单例MongoDB工具类
    配置SpringMVC返回JSON遇到的坑
    DRF---序列化器-Serializer
    面试题--web(django)
    DRF----web应用模式
    面试题--网络编程
    Vue-项目之免费课和购物车实现
    面试题--面向对象
    vue- 项目之前端页面搭建1
  • 原文地址:https://www.cnblogs.com/6bing/p/3931229.html
Copyright © 2011-2022 走看看