Trying to fix the logic. Still need to fix the case where there is no gcd.