您的位置:首页 > 其它

欧几里得算法与其扩展 Romantic

2017-03-21 23:21 218 查看
1.欧几里得算法长用于求最小公倍数和最大公因子gcd

    gcd(a,b)=gcd(b,a%b).代码模板如下:

int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}


求N!的素因子P个数:

肯定有:P,2P,3P……[N/P]P  所以至少有N/P个素因子,提取出P因子之后为1*2*3*……[N/P],

1.如果和N!相同,则结果为N/P个,

2.如果不同,则结果为N/P+刚刚的阶乘中P因子的个数直到没有P因子

 

智力题:25!中有多少个素因子5

6个:5,10,15,20,25=5*5

100!中末尾有多少个0

思路:10=2*5(出现零的情况必须有5),但2出现的情况太多,所以只考虑5的个数

2.欧几里得算法的扩展

其扩展常用与已知整数a,b,求整数解满足a*x+b*y=gcd(a,b)的关系

由数论知识可知:a*x+b*y=gcd(a,b)=gcd(b,a%b).

解:gcd(a,b)=gcd(b,a%b)=b*X+a%b*Y=b*X+(a-a/b*b)*Y=a*Y+b*(X-Y*a/b)与a*x+b*y一一对应

得:x=Y,y=(X-Y*a/b)

根据欧几里得的结论:在不断减小的过程,直到b为0的时候(找出最大公因子)x=1,y=0,之后层层递推得到x,y。

考虑a*x+b*y=c的情况

1)如果c不为gcd的整数倍数,方程无解

2)如果c=g,得到一组解(x0,y0),如果c是g的倍数,则对应解为(x0*c/g,y0*c/g)。

3)如果得到一组特解(x,y),则通解为(x+k*b/g,y-k*a/g)代入可以验证等于原式子

 

 


Problem Description

The Sky is Sprite.

The Birds is Fly in the Sky.

The Wind is Wonderful.

Blew Throw the Trees

Trees are Shaking, Leaves are Falling.

Lovers Walk passing, and so are You. 

................................Write in English class by yifenfei


 

Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!

Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.


Input

The input contains multiple test cases.

Each case two nonnegative integer a,b (0<a, b<=2^31)


Output

output nonnegative integer X and integer Y, if there are more answers than the X smaller one will be choosed. If no answer put "sorry" instead. 


Sample Input

77 51
10 44
34 79



Sample Output

2 -3
sorry
7 -3


 题意:现在告诉你两个非负整数a和b。 找到非负整数X和整数Y以满足X * a + Y * b = 1。如果没有这样的答案打印“sorry”。输出非负整数X和整数Y,如果有更多的答案比X更小的一个将被选择。 如果没有回答就放在“sorry”。
#include <iostream>
#include<cstdio>
using namespace std;
int x,y;
int gcd(int a,int b)
{ //欧几里得算法的扩展
int t,g;
if(b==0){
x=1;y=0;
return a;
}
g=gcd(b,a%b);
t=x;
x=y;
y=t-a/b*y;
return g;
}
int main()
{
int a,b;
while(scanf("%d%d",&a,&b)==2)
{
int g=gcd(a,b);
if(g!=1)
printf("sorry\n");
else
{ while(x<=0)
{
x=x+b;
y=y-a;
}
printf("%d %d\n",x,y);
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: