3102. 【NOIP2012提高组】同余方程
Description
求关于x的同余方程ax ≡ 1 (mod b)的最小正整数解。
Input
输入文件为 mod. in。
输入只有一行,包含两个正整数 a, b,用一个空格隔开。
Output
输出文件为mod.out。
输出只有一行,包含一个正整数 x ,即最小正整数解。输入数据保证一定有解。
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。
solution
这不就是个裸的扩展欧几里得嘛。
ax ≡ 1 (mod b)
ax ≡ by+1
ax-by ≡ 1
乱搞即可。
code
#include<cstdio>
using namespace std;
int a,b,x,y,t;
int exgcd(int a,int b)
{
	if (!b) x=1,y=0;
	else
	{
		exgcd(b,a%b);
		t=y,y=x-(a/b)*y,x=t;
	}
}
int main()
{
	scanf("%d%d",&a,&b);
	exgcd(a,b);
	if (x>b) printf("%d\n",x%b);
	else if (x<0) printf("%d\n",x%b+b);
	else printf("%d\n",x);
}
                                    
    转载需注明出处。
                    
                
                
            
        
浙公网安备 33010602011771号