UVA 10673 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 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 that x 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

 



题意:给定x,k。 a = x / k取下整, b = x / k 取上整, 求出x = p * a + q * b时p和q的值。

思路:参考了题解http://www.cnblogs.com/scau20110726/archive/2013/02/01/2889556.html并且了解了下扩展欧几里得算法。有点理解了。

代码:

#include <stdio.h>
#include <math.h>

int T;
long long a, b, c, d, k, x, y;

void gcd(long long a, long long b, long long &d, long long &x, long long &y) {
	if (!b) {d = a; x = 1; y = 0;}
	else {gcd(b, a % b, d, y, x); y = y - x * (a / b);}
}

int main() {
	scanf("%d", &T);
	while (T --) {
		scanf("%lld%lld", &c, &k);
		a = floor(1.0 * c / k);
		b = ceil(1.0 * c / k);
		gcd(a, b, d, x, y);
		x *= c / d;
		y *= c / d;
		printf("%lld %lld\n", x, y);
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值