uva 10673Play with Floor and Ceil(擴展歐幾里得算法)

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 integers p 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 of x 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 integers x and k. You can safely assume thatx and k 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 of p 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

 


Problem setter: Monirul Hasan, Member of Elite Problemsetters' Panel

Special Thanks: Shahriar Manzoor, Member of Elite Problemsetters' Panel



題目大意:求出滿足要求的p和q,使得對於給定的x,k,,輸出一組滿足要求的p,q即可;

下面對於x,k進行討論;

1、若x能被k整除,那麼只要p+q=k即可;

2、如果不能被其整除,則領,那麼,x=p*a+q*(a+1);相當於對於不定方程求解,易知,(a,a+1)=1,所以可以先用擴展歐幾里得算法求出一組滿足

1=a*x+(a+1)*y;的解,x,y,然後在同時乘以x即可;

代碼:

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<vector>
#include<stdlib.h>
#include<string>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<set>
#define inf 0x3f3f3f3f
#define eps 1e-5
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
using namespace std;
typedef long long LL;
LL exc_gcd(LL a,LL b,LL &x,LL &y)
{
    if(!b)
    {
        x=1,y=0;
        return a;
    }
    LL g=exc_gcd(b,a%b,x,y);
    LL t=x;
    x=y;
    y=t-(a/b)*y;
    return g;
}
int main()
{
    int n,t,x,k;
    while(~scanf("%d",&t))
    {
        while(t--)
        {
            scanf("%d%d",&x,&k);
            if(x%k==0)
            {
                printf("%d %d\n",0,k);
            }
            else
            {
                LL a=x/k;
                LL x1,y;
                LL gg=exc_gcd(a+1,a,x1,y);
                ///if(x<0) x+=
                y=x*y;
                printf("%I64d %I64d\n",y,x*x1);
            }
        }
    }
    return 0;
}


 

發佈了181 篇原創文章 · 獲贊 11 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章