Search code examples
c++functiongreatest-common-divisor

Greatest Common Factor


so I tried to make a function to find a GCD (Greatest Common Divisor) for my friend who just started learning C++ (I have some basic knowledge of C++). So here's my code:

int gcd(int var1, int var2){
    int result;
    if(var1<1 || var2<1){
        return 0; //means error
    } else {
        for(int i=0; i<=var1 && i<=var2; i++){
            if((var1%i) == 0 && (var2%i) == 0){
                result = i;
            }
        }
    }
    return result;
}

It compiled, but the problem is the .exe stopped working whenever it tries to use the operator '%'. In this case, at this line of code: var1%i and var2%i. So, I tried to tweak the code a little bit into this:

int gcd(int var1, int var2){
    int result;
    if(var1<1 || var2<1){
        result = 0; //means error
    } else {
        for(int i=var1; i>=1; i--){
            if((var1%i) == 0 && (var2%i) == 0){
                result = i;
                break;
            }
        }
    }
    return result;
}

And it worked without any problem. So, I was wondering what is the problem with the first code?


Solution

  • You can't % by 0 because it will generate a divide-by-zero exception. You need to start i at 1 instead of 0 in the first loop.