同余与扩展欧几里得解模线性方程——CLooooops(POJ 2115)

  • 题目链接:
    http://poj.org/problem?id=2115

  • 分析:
    题目大意为求解能使得 A + x * C = B 的最小的x
    , 0 ≤ x < 2^k .

  • 题解:
    我们可以先构造模线性方程,原式转换为 x * C = B - A ,即有 C*x = B - A (mod 2^k),(此处用到了模运算规则),得出标准模线性方程,利用扩展欧几里得即可求解。

  • 注意:int类型的移位计算如果超过30位会导致结果不准确,所以需要使用_int64 整数类型。

  • AC代码:

#include <iostream>
#include <cstdio>
using namespace std;

__int64 x, y;

__int64 Extended_Euclid(__int64 a, __int64 b) {
      if (b == 0) {
         x = 1;
         y = 0;
         return a;
      }
      __int64 m = Extended_Euclid(b, a % b);
      __int64 tmp = x;
      x = y;
      y = tmp - a / b * y;
      return m;
}

int main()
{
    __int64 a, b, c, k;

    while (scanf ("%I64d%I64d%I64d%I64d", &a, &b, &c, &k)) {
        if (!a && !b && !c && !k) break;
        __int64 d = (__int64)1<<k; //此处先讲1转化为64位,否则系统默认1为int型,右移32位会溢出
        __int64 e = Extended_Euclid(c, d);
        if ((b-a) % e) { printf ("FOREVER\n"); continue; }
        __int64 t = d / e;
        x = (x  * (b - a) / e % t + t) % t;
        printf ("%I64d\n", x);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值