Reputation: 13
First question here, so sorry if my formatting is a bit off.
I'm trying to write a code involving greatest common divisor in c++ as part of a homework assignment. However, whenever I go to build my code, I immediately get a "program is not responding" message. I've tried a basic Hello World code and it compiled fine. Here is my code.
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == a) return a;
else return gcd(b, a%b);
}
int main()
{
gcd(25,10);
return 0;
}
I've tried many different values in calling gcd, but almost all seem to give me the same error. It seems to happen when calling the outside function in main, whenever the "else" line of code is used. I really don't know what to make of it. Am I missing something simple? Thanks.
Upvotes: 1
Views: 108
Reputation: 11414
A call with 25,10:
Modulo (division) with 0 isn´t possible (without going into high-level math stuff,
something the CPU won´t do). You can check the crash in your debugger, it should
print more helpful information than the standard windows message.
Simple solution: Check if b is 0 with a if
before.
Upvotes: 1