NOIP 2012 同余方程

洛谷 P1082 同余方程

洛谷传送门

JDOJ 1782: [NOIP2012]同余方程 D2 T1

JDOJ传送门

Description

求关于 x 的同余方程 ax ≡ 1 (mod b)的最小正整数解。

Input

输入只有一行,包含两个正整数 a, b,用一个空格隔开。

Output

输出只有一行,包含一个正整数x0,即最小正整数解。输入数据保证一定有解。

Sample Input

3 10

Sample Output

7

HINT

对于40%的数据,2 <= b <= 1,000;

对于60%的数据,2 <= b <= 50,000,000;

对于100%的数据,2 <= a, b <= 2,000,000,000。

Source

NOIP2012提高组

题解:

由同余的概念,这道题至少40pts:

#include<cstdio>
using namespace std;
int a,b;
int main()
{
    scanf("%d%d",&a,&b);
    for(int i=1;i<=100000000;i++)
        if((a*i)%b==1)
        {
            printf("%d",i);
            return 0;
        }
    return 0;
}

稍微往深想一下,发现如果(axequiv 1(mod\,\,\,b)),那么(ax)肯定是(b)的倍数加一,那么有了下面的代码,数据比较水能骗70分:

#include<cstdio>
#define int long long
using namespace std;
int a,b;
signed main()
{
    scanf("%lld%lld",&a,&b);
    int i=1;
    while((b*i+1)%a)
        i++;
    printf("%lld",(b*i+1)/a);
    return 0;
}

但是实际上这是一道扩展GCD的裸题。满分做法需要使用扩展GCD:

如果有对扩展GCD不熟悉的小伙伴请移步本蒟蒻的博客:

浅谈扩展GCD

代码:

#include<cstdio>
#define ll long long
using namespace std;
ll a,b,x,y,k;
void exgcd(ll a,ll b)
{
    if(!b)
    {
        x=1;
        y=0;
        return;
    }
    exgcd(b,a%b);
    k=x;
    x=y;
    y=k-a/b*y;
    return;
}
int main()
{
    scanf("%lld%lld",&a,&b);
    exgcd(a,b);
    printf("%lld",(x+b)%b);
    return 0;
}
原文地址:https://www.cnblogs.com/fusiwei/p/11773601.html