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

本文介绍了如何通过扩展欧几里德算法解决整数方程问题,具体步骤包括求解m'm + n'n = gcd(m,n)的m'和n',并提供了一个简单的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值