HDU - 1722:分蛋糕(最大公约数)

原题链接
Problem Description
一次生日Party可能有p人或者q人参加,现准备有一个大蛋糕.问最少要将蛋糕切成多少块(每块大小不一定相等),才能使p人或者q人出席的任何一种情况,都能平均将蛋糕分食.
Input
每行有两个数p和q.
Output
输出最少要将蛋糕切成多少块.
Sample Input
2 3
Sample Output
4

Hint
将蛋糕切成大小分别为1/3,1/3,1/6,1/6的四块即满足要求.
当2个人来时,每人可以吃1/3+1/6=1/2 , 1/2块。
当3个人来时,每人可以吃1/6+1/6=1/3 , 1/3, 1/3块。

题目描述

切蛋糕,保证来p或q个人都能平分

思路:我们可以将蛋糕分别平均分为p份和q份,使他们切的刀数尽可能的重合,那么剩下的就是需要切的刀数,即蛋糕的块数:p+q-__gcd(p,q)

值得一提的是在求最大公约数时,我们可以调用函数库里面的__gcd(p,q)函数

代码如下

#include <stdio.h>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int p,q;
    while(~scanf("%d %d",&p,&q))
        printf("%d\n",p+q-__gcd(p,q));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43327091/article/details/87901772