uva10673 - Play with Floor and Ceil 扩展欧几里德算法

Problem A
Play with Floor and Ceil
Input:
standard input
Output: standard output
Time Limit: 1 second
 

Theorem

For any two integers x and k there exists two more integersp and q such that:

It’s a fairly easy task to prove this theorem, so we’d not ask you to do that. We’d ask for something even easier! Given the values ofx and k, you’d only need to find integers p and q that satisfies the given equation.

 

Input

The first line of the input contains an integer, T (1≤T≤1000) that gives you the number of test cases. In each of the following T lines you’d be given two positive integersx and k. You can safely assume that x andk will always be less than 108.

 

Output

For each of the test cases print two integers: p and q in one line. These two integers are to be separated by a single space. If there are multiple pairs ofp and q that satisfy the equation, any one would do. But to help us keep our task simple, please make sure that the values, and fit in a 64 bit signed integer.

 

Sample Input                              Output for Sample Input

3

5 2

40 2

24444 6

1 1

1 1

0 6


  这个题还有其他简单方法,就不说了,来看看扩展欧几里德算法。

  扩展欧几里德算法用来算m'm+n'n=gcd(m,n)的m'和n'(一定有解)。

  设r=m mod n,n''n+r'r=gcd(n,r)=gcd(m,n)

  因为r=m-(m/n)*n,把这个代入上式得 n''n+r'(m-(m/n)*n)=gcd(n,r)=gcd(m,n),也就是r'm+(n''-r'*m/n)n=gcd(m,n)

  所以只要求出n''和r',m'和n'也就求出来了。

  m'=r',n'=n''-r'*m/n=n''-m'*m/n

  若n==0,由于gcd(m,0)=m,所以让m'=1,n'=0就行了。

//求ax+by=gcd(a,b),d=gcd(a,b),d,x,y是引用,注意参数位置
void gcd(int a,int b,int &d,int &x,int &y){
    if(!b){
        d=a;
        x=1;
        y=0;
    }
    else{
        gcd(b,a%b,d,y,x); //注意x和y位置调换
        y-=x*(a/b);
    }
}

  这道题是一定有解的,因为取顶和底要么差1,要么相等。

代码:

#include<cstring>
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
void gcd(int a,int b,int &d,int &x,int &y){
    if(!b){
        d=a;
        x=1;
        y=0;
    }
    else{
        gcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
int main(){
    //freopen("in.txt","r",stdin);
    int T,N,K;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&N,&K);
        int a=floor(1.*N/K),b=ceil(1.*N/K),d,p,q;
        gcd(a,b,d,p,q);
        printf("%d %d\n",p*N/d,q*N/d);
    }
    return 0;
}



你可能感兴趣的:(uva10673 - Play with Floor and Ceil 扩展欧几里德算法)