[HDU] [1722] Cake

Problem Description

Loading...

Problem Analysis

You can actually figure it out by finding the pattern

The pattern can be explained like this: if we want to be able to split it into p equal parts or q equal parts, we can first split it into d (greatest common divisor) = gcd(p,q) parts, because once you have split it into d parts, you can either choose to split each part into p/d parts (that is, split the whole into p parts), or choose to split each part into q/d parts (that is, split the whole into p parts). Among these two choices, there definitely won’t be a cut that lands on the same position! So we get the formula: s=p+q-gcd(p,q);

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include<stdio.h>
int gcd(int a,int b) {
    if(b==0)
        return a;
    return gcd(b,a%b);
}
int main() {
    int n,m;
    while(scanf("%d %d",&n,&m)!=EOF)
        printf("%d\n",n+m-gcd(n,m));
    return 0;
}

Loading...