Trying to implement gcd int function using Euclidean Algorithm with recursion. Results from CodeBlocks differ from IDEone (which I use to test my code before submitting to a CP website, TLX: https://tlx.toki.id, which I assume has similar compilers etc. because a lot of times IDEone and TLX got RTE while in CodeBlocks it ran without any problem). First Question: 1. Do they actually have something different that affects the output?
My first attempt was as follows:
#include <iostream>
#include <cmath>
using namespace std;
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#define pass (void)0
#include <cstdio>
#include <cstring>
#define ll long long
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which IDEone spits out
Runtime error #stdin #stdout 0.01s 5380KB
test
while it ran as expected (z = 1
and prints out the correct stuff) in CodeBlocks
I tried to pinpoint where the error exactly occurs by 1. printing out at what part of the code my computer went error by the following way
void gcd(int x, int y){
if(y!=0){
cout << "if " << x << ", " << y << endl;
gcd(y, x%y);
} else {
cout << "else " << x << ", " << y << endl;
//return x;
}
}
int main() {
cout << "test" << endl;
//int z = gcd(100, 10);
gcd(100, 10);
//cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which in both IDE, it outputted:
test
if 100, 10
else 10, 0
hello
then I also tried:
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
CodeBlocks outputted the first, while IDEone had an error as in the second
test
10 bruh
hello
Runtime error #stdin #stdout 0.01s 5380KB
test
from what I've tried and understand so far, it seems there's an error when the function gcd() calls the gcd() function. 2. Is my assumption correct? 3. and how am I supposed to solve this problem?
Thanks in advance
CodePudding user response:
The problem is that the recursive case of the gcd()
function does not run a return
statement. Thus, it should be modified like this:
int gcd(int x, int y){
if(y!=0){
return gcd(y, x%y);
} else {
return x;
}
}
This could easily have been caught by enabling and reading compiler warnings.