(8 pts) Consider the following C codes to compute the gcd of two integers. /// c
ID: 3891198 • Letter: #
Question
(8 pts) Consider the following C codes to compute the gcd of two integers.
/// code 1
#include <stdio.h>
int gcd(int a, int b) {
while (a != b) {
if (a > b) a = a - b;
else b = b - a;
}
return a;
}
/// code 2
#include <stdio.h>
int getint() {
int i;
scanf("%d", &i);
return i;
}
void putint(int i) {
printf("%d ", i);
}
int main() {
int i = getint(), j = getint();
while (i != j) {
if (i > j) i = i % j;
else j = j % i;
}
putint(i);
}
Do code 1 and code 2 work correctly? Why and why not? Can you fix the one(s) not working (if any?) Which one is faster? Explain.
Explanation / Answer
Hello,
1. From the above two codes Code 1 will surely work since it is an simple recursive gcd calculation technique. (subraction method)
2.Code 2 will not work because it has floating point error and when you compile it. It will show 'Floating point execution error'
3.If Code 2 properly works it will be faster when compared with code 1. Since almost the work is reduced enormously in code 2 .whereas in code 1 it is not.
Hope, I have solved your problem.
Thank you:) Have a pleasant day :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.