This function has to return some int — that’s the compiler error here.
However there are many other issues.
- the gcd of two coprime numbers is 1, by definiton. If a and b are coprime then the
return
in the for loop is never encountered. - the return in the for loop is never encountered for negative a or b either, as tkausl points out
- even if the loop runs, there’s a bug in it. For any
a>=0
andb>=0
you’re going to return 1 wheni = 1
, becausea % 1 == 0 && b % 1 == 0
is always true.
int hcf (int a, int b) {
int gcd;
for (int i = 0; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0) { /* <<< wrong <<< */
gcd = i;
return gcd;
}
}
// a and b have no common divisor
return 1;
}