samedi 19 décembre 2020

Find the number of steps transforming a/b into c/d so that 0

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 (1) {
        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 !

Aucun commentaire:

Enregistrer un commentaire