GCD
Aug 25, 2013 at 10:54am UTC
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

Aug 25, 2013 at 12:10pm UTC
Your function has undefined behaviour. It does not return any value in case then the outer loop finished its iterations.

Aug 25, 2013 at 12:19pm UTC
i corrected it i put

Out of the outer loop but still its giving wrong answers

Aug 25, 2013 at 12:28pm UTC
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 Aug 25, 2013 at 12:43pm UTC

Aug 25, 2013 at 12:34pm UTC
im sorry i didnt understand ur function, it should find the largest number that divides all the array elements without remainder

Aug 25, 2013 at 12:40pm UTC
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 Aug 25, 2013 at 12:42pm UTC

Aug 25, 2013 at 1:01pm UTC
oh thanks for helping me, many times i repeat this error

Topic archived. No new replies allowed.