Three Jugs(辗转相除法求GCD)

本文介绍了一个有趣的数学问题——利用三个容量不同的壶如何得到精确的水量,并通过计算最大公约数的方法给出了程序解决方案。

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



Description

    We have three jugs A, B, C without any calibration, and an infinite supply of water. There are three types of actions that you can use:
     (1) Fill a jug.
     (2) Empty a jug.
     (3) Pour from one jug to another.
    Pouring from one jug to another stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons, B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A.
    Now you need to calculate the minimum accurate gallons of water we can get by using the three jugs.


Input

    There is an integer T (1 <= T <= 200) in the first line, means there are T test cases in total.
    For each test case, there are three integers a, b, c (1 <= a, b, c <= 10^18) in a line, indicate the capacity (unit: gallon) of the three jugs.


Output

    For each test case, you should print one integer in a line, indicates the minimum accurate gallons of water we can get by using the three jugs.


Sample Input

2
3 6 9
6 10 15

Sample Output

3
1

HINT

找3个数的最大公约数
#include<stdio.h>
unsigned long   long   gcd(unsigned long   long   a,unsigned long   long   b)
{
if(a==0)
return   b;
else
return   gcd(b%a,a);
}
int   main()
{
int   t;
unsigned long   long   a,b,c,ans;//记得改回long long
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
scanf("%lld %lld %lld",&a,&b,&c);
ans=gcd(a,gcd(b,c));
printf("%lld\n",ans);
}
}
return   0;
}
虽然并没有明白为什么是最大公约数。。。
这里是GCD的一点知识:
求法:辗转相除法  辗转相除法是求两个自然数的最大公约数的一种方法,也叫欧几里德算法
这就是辗转相除法的原理。
辗转相除法的格式 辗转相除法的格式
例如,求(319,377):
∵ 319÷377=0(余319)
∴(319,377)=(377,319);
∵ 377÷319=1(余58)
∴(377,319)=(319,58);
∵ 319÷58=5(余29),
∴ (319,58)=(58,29);
∵ 58÷29=2(余0),
∴ (58,29)= 29;
∴ (319,377)=29.
可以写成右边的格式。
用辗转相除法求几个数的最大公约数,可以先求出其中任意两个数的最大公约数,再求这个最大公约数与第三个数的最大公约数,依次求下去,直到最后一个数为止。最后所得的那个最大公约数,就是所有这些数的最大公约数
c语言实现的话代码中已经有了,而且比百度百科上的简单的多
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值