Search code examples
c++if-statementwhile-loopequationfractions

Find the number of steps transforming a/b into c/d so that 0<a<b<100000 and 0<c<d<100000, or none if there is no ways


Original problem. Given two valid fractions a/b and c/d. Each transformation is adding 1 to a and b, then optimizing a/b. Find the number of steps transforming a/b into c/d so that 0<a<b<100000 and 0<c<d<100000, or none if there is no ways.

#include <iostream>
#include <math.h>
using namespace std;
int gcd(int x, int y) {
    while(y) {
        int r=x%y;
        x=y;
        y=r;
    }
    return x;
}
int main() {
    int a, b, c, d;
    cin>>a>>b>>c>>d;
    int i=0;
    while (b<d) {
        if (a*d<b*c) {
            a++;
            b++;
            a/=gcd(a, b);
            b/=gcd(a, b);
            i++;
        }
        else if (a*d==b*c) {
            cout<<i;
            break;
        }
        else {
            cout<<0;
            break;
        }
    }
}

Something wrong, i.e., for input

1
6
2
3

The answer is 5, but not an output here.. I need to the help, thanks for all your nice comments !


Solution

  • The first problem is while (b<d). In your example 6<3 is wrong so the while loop is completely skipped.

    The next problem is

    a/=gcd(a, b);
    b/=gcd(a, b);
    

    You are changing a and calculating two different gcd for a and b.

    You can fix it with

    const auto g = gcd(a, b);
    a/=g;
    b/=g;