Exercise 3. The Euclidean Algorithm The Euclidean algorithm to find the greatest
ID: 2256215 • Letter: E
Question
Exercise 3. The Euclidean Algorithm The Euclidean algorithm to find the greatest common di- visor (ged) of two integers a and b, i.e., the largest integer that divides both a and b, can be described as follows: If a0 then gcd(a, b)-gcd(0, b)b If b 0 then gcd(a, b) = gcd(a, 0) = a If a b then ged(a, b) = gcd(b, b)-b Write a = b * q + r and calculate ged(a, b) = gcd(b, r). For example gcd(270, 192) -6 Write a MATLAB program which for two numbers a and b determines their greatest common divisor gcd (a,b), .e. function gcd.val - gcd (a,b)Explanation / Answer
MATLAB code
close all
clear
clc
fprintf('gcd(270,192) = %d ', gcd(270,192));
function gcd_val = gcd(a,b)
if a == 0
gcd_val = b;
else
if b == 0
gcd_val = a;
else
if a == b
gcd_val = b;
else
gcd_val = gcd(b,rem(a,b));
end
end
end
end
output
gcd(270,192) = 6
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.