GCD

i wrote this GCD function to find gcd of an array of numbers
here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
long long GCD(long long min,int loc,long long b[])
{
	for (long long i=min;i>0;i--)
	{
		bool p=0;
		for (long long x=0;x<loc;x++)
		{
			if (b[x]%i!=0)
			{
				p==1;
				break;
			}
		}
		if (p==0)
			return i;
	}
}

its returning wrong answers, please help
when i tried 6 14 it returns 6
Your function has undefined behaviour. It does not return any value in case then the outer loop finished its iterations.
i corrected it i put
 
return 0;

Out of the outer loop but still its giving wrong answers
If I have correctly understood the task your function could look the following way

1
2
3
4
5
6
7
8
9
unsigned long long GCD( unsigned long long a[], size_t n, unsigned long long min )
{
	unsigned long long i = min;

	while (  i > 1 && 
	         !std::all_of( a, a + n, std::not1( std::bind2nd( std::modulus<int>(), i ) ) ) i--;

	return i;
}
Last edited on
im sorry i didnt understand ur function, it should find the largest number that divides all the array elements without remainder
Here you use the comparison operator instead of the assignment operator.

1
2
3
4
5
			if (b[x]%i!=0)
			{
				p==1;
				break;
			}
Last edited on
oh thanks for helping me, many times i repeat this error
Topic archived. No new replies allowed.