Eulidian Algorythim

1
2
3
4
5
6
7
8
9
10
11
12
13
int[code] gcd( int x , int y)
{
	int  r = x & y;
	while (r != 0)
	{
		x = y;
		y = r;
		r = x % y;
		return r;


	}
}

[/code]

is this the correct way to find the GCD???

Last edited on
I think it's simpler than that. The main problem is that you have return r; inside the while loop. That means that you'll return after the first run of the loop. That means you'll never actually loop.

Try this out:
1
2
3
4
5
6
7
8
9
int gcd( int x , int y)
{
    while (y != 0)
    {
        int z = y;
        y = x % y;
        x = z;
    }
}


Or if you are into recursion:
1
2
3
4
5
int gcd( int x, int y)
{
    if (y == 0) return x;
    return gcd(y, x%y);
}
Last edited on
Topic archived. No new replies allowed.