414 views

Consider the following C functions:

int f1(int a, int b)
{
while (a != b)
{
if(a > b)
a = a - b;
else
b = b - a;
}
return a;
}
int f2(int a, int b)
{
while (b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
int f3(int a, int b)
{
while (a != 0)
{
int t = a;
a = b % a;
b = t;
}
return b;
}
1. All 3 functions return same value for all positive inputs
2. f1 and f2 return same value for all positive inputs but not f3
3. For some positive input all 3 functions return different values
4. f2 and f3 return same value for all positive inputs but not f1

edited | 414 views

All three functions are same.
Function calculates GCD of numbers 'a' and 'b'.
by Veteran (60k points)
selected by
+3

Sir, what if a= 3, b=0, then

I think, f1 will go in an infinite loop.

int f1(int a, int b)
{
while (a != b)
{
if(a > b)
a = a - b;
else
b = b - a;
}
return a;
}


isn't it  ??

and f2 and f3 will result 3 ..

??

0
yes, it should have mentioned "positive inputs" :(
+1
sir, Just by seeing option D, I thought of edge case, otherwise, all are doing the same job but not for all integers.
0
@Arjun sir, if we use a=5 and b=2, then all are different .
+1
i got same 1 as output.
0
yes, right i made a big mistake .
+1
i also done just run while loop 1 time in 1st case. :)
0
int f1(int a, int b)
{
while (a != b)
{
if(a > b)
a = a - b;
else
b = b - a;
}
return a;
}
int f2(int a, int b)
{
while (b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
int f3(int a, int b)
{
while (a != 0)
{
int t = a;
a = b % a;
b = t;
}
return b;
}
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char* argv[])
{
if(argc < 2){
fprintf(stderr, "Please enter 2 numbers and retry\n");
exit(0);
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("f1: %d\n", f1(a,b));
printf("f2: %d\n", f2(a,b));
printf("f3: %d\n", f3(a,b));

}

./a.out 12 13
f1: 1
f2: 1
f3: 1

0
i got 121 is output how it same for all the options??
0
For which input?
0
Thanku so much sir ! for replying

input i taken a=5 & b=2
0

I just ran it

[email protected]:~\$ ./a.out 5 2
f1: 1
f2: 1
f3: 1

0
a=5 b=2

2!=0 [right]

t=2

b=a%b i.e 2

a=2

return 2

where i am wrong please correct me!
all 3 function are same
by (111 points)

1
2
+1 vote