HDU 1576 A/B 扩展欧几里得

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1576

思路:此处来自百度:设(A/B)%9973 = K, 则A/B = k + 9973x  (x未知), 因此A = kB + 9973xB,

又A%9973 = n, 所以kB%9973 = n,  故kB = n + 9973y (y未知)

故(k/n)B +(-y/n)*9973 = gcd(B,9973) = 1

扩展欧几里得 求出k/n,  再乘以个n,记得取模,就是answer了

#include <iostream>
#include <cstdio>
#include <functional>
#include <algorithm>
#include <cstring>
using namespace std;

typedef long long ll;
int x, y;
int extgcd(int a, int b, int &x, int &y)
{
    int d = a;
    if(b != 0)
    {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    }
    else x = 1, y = 0;

    return d;
}

int main()
{
    int t, n, b;

    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &b);
        extgcd(b, 9973, x, y);
        x = (x % 9973 + 9973) % 9973;//求出来的x可能是负数,此处矫正
        printf("%d\n", (x*n)%9973);
    }

    return 0;
}

下面是本人当初写这道题时写的暴力代码,没什么好说的

#include <iostream>
#include <cstdio>
#include <functional>
#include <algorithm>
#include <cstring>
using namespace std;

typedef long long ll;

int main()
{
    int t, n, b;

    scanf("%d", &t);
    while(t--)
    {
        ll a;
        scanf("%d%d", &n, &b);
        if(b > 9973) //b和9973谁较大就用谁往上累加,直到找到合适的a
        {
            for(a = b; a % 9973 != n; a += b);
            printf("%lld\n", a / b % 9973);
        }
        else
        {
            for(a = n; a % b != 0; a += 9973);
            printf("%lld\n", a / b % 9973);
        }
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值