首页 > ACM题库 > HDU-杭电 > hdu 2669 Romantic-数论-[解题报告]C++
2014
02-12

hdu 2669 Romantic-数论-[解题报告]C++

Romantic

问题描述 :

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.

输入:

The input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)

输出:

The input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)

样例输入:

77 51
10 44
34 79

样例输出:

2 -3
sorry
7 -3

转载请注明出处忆梦http://blog.csdn.net/yimeng2013/article/details/11822563

#include<cstdio>
int x, y;
int gcd(int a,int b)
{// x,y用全局变量保存
    int t,d;
    if(b==0)
    {
        x=1;
        y=0;   
		return a;
    }
    d=gcd(b,a%b);
    t=x;
    x=y;
    y=t-(a/b)*y; 
	return d;
}


int main ()
{
	int a, b;
	while(~scanf("%d %d", &a, &b))
	{
		int d = gcd(a, b);
		if(d != 1)
		{
			printf("sorry\n");
			continue;
		}
		
		while(x <= 0)
		{
			x = x + b;
			y = y - a;
		}
		printf("%d %d\n",x, y);
	}
	return 0;
}

解题转自:http://blog.csdn.net/yimeng2013/article/details/11822563


  1. 漂亮。佩服。
    P.S. unsigned 应该去掉。换行符是n 不是/n
    还可以稍微优化一下,
    int main() {
    int m,n,ai,aj,bi,bj,ak,bk;
    while (scanf("%d%d",&m,&n)!=EOF) {
    ai = sqrt(m-1);
    bi = sqrt(n-1);
    aj = (m-ai*ai-1)>>1;
    bj = (n-bi*bi-1)>>1;
    ak = ((ai+1)*(ai+1)-m)>>1;
    bk = ((bi+1)*(bi+1)-n)>>1;
    printf("%dn",abs(ai-bi)+abs(aj-bj)+abs(ak-bk));
    }
    }