Here is the problem we should solve with C++:
GCD ( 2m , 2n ) = 2 * GCD( m , n )
GCD ( 2m , 2n+1 ) = GCD ( m , 2n+1 )
GCD ( 2m+1, 2n+1 ) = GCD ( n-m , 2m+1 ) (m<n)
GCD ( m , m ) = m
and here is the function i wrote:
int GCD(int n1, int n2)
{
bool n1Zoj, n2Zoj;
n1Zoj = (n1%2 == 0);
n2Zoj = (n2%2 == 0);
if(n1Zoj && n2Zoj)
return 2 * GCD(n1/2, n2/2);
if(n1Zoj && !n2Zoj)
return GCD(n1/2, n2);
if(!n1Zoj && !n2Zoj)
return GCD((n2-n1)/2, n1);
if(n1 == n2)
return n1;
}
(*”Zoj” means “Even” in my language(persian) )
when i pass 5 as the second argument, program crashes and prints this message:
Segmentation fault (core dumped)
Exit code is 139. I’m using Code::Blocks on ubuntu 12.04 that uses g++ as compiler.
UPDATE: Program crashes with 5,10,15,20,25,…
UPDATE: i think the correct form of function is:
int GCD(int n1, int n2)
{
if (n1 > n2)
std::swap(n1, n2);
//std::cout<<"GCD is called with params: "<<n1<<" & "<<n2<<std::endl;
bool n1Zoj, n2Zoj;
n1Zoj = (n1%2 == 0);
n2Zoj = (n2%2 == 0);
if(n1 == n2)
return n1;
if(n1Zoj && n2Zoj)
return 2 * GCD(n1/2, n2/2);
if(n1Zoj && !n2Zoj)
return GCD(n1/2, n2);
if(!n1Zoj && n2Zoj)
return GCD(n2/2, n1);
if(!n1Zoj && !n2Zoj)
return GCD((n2-n1)/2, n1);
}
When
(n1Zoj && n2Zoj)evaluates to true, what do you do? You callwhich calls the function with the exact same parameters, resulting in infinite recursion, a blown out stack, and a stack overflow (segmentation fault).
Protip – learn to debug – I can’t emphasize how extremely important this is.