Calculating Greatest Common Divisor using While loop
Instead of using built in ‘GCD’ function, I am to devise code to calculate the GCD of two numbers using a while loop. I cannot figure out how to code it. Requesting some help!
%% Input two numbers.
% There is no error checking so put in positive integers of bad things may
% happen – MC
x = input(‘Enter an integer > 0: ‘);
y = input(‘Enter another integer > 0: ‘);
if x >= y
numerator = x;
denominator = y;
else
numerator = y;
denominator = x;
end
%% Calculates the GCD
% ———— Replace this piece of the code with a while loop ———–
r = rem(numerator, denominator);
while r > 0
if r == 0
GCD = denominator;
break;
end
end
fprintf(‘The GCD of %d and %d is %d: it took calculationsn’,x,y,GCD)Instead of using built in ‘GCD’ function, I am to devise code to calculate the GCD of two numbers using a while loop. I cannot figure out how to code it. Requesting some help!
%% Input two numbers.
% There is no error checking so put in positive integers of bad things may
% happen – MC
x = input(‘Enter an integer > 0: ‘);
y = input(‘Enter another integer > 0: ‘);
if x >= y
numerator = x;
denominator = y;
else
numerator = y;
denominator = x;
end
%% Calculates the GCD
% ———— Replace this piece of the code with a while loop ———–
r = rem(numerator, denominator);
while r > 0
if r == 0
GCD = denominator;
break;
end
end
fprintf(‘The GCD of %d and %d is %d: it took calculationsn’,x,y,GCD) Instead of using built in ‘GCD’ function, I am to devise code to calculate the GCD of two numbers using a while loop. I cannot figure out how to code it. Requesting some help!
%% Input two numbers.
% There is no error checking so put in positive integers of bad things may
% happen – MC
x = input(‘Enter an integer > 0: ‘);
y = input(‘Enter another integer > 0: ‘);
if x >= y
numerator = x;
denominator = y;
else
numerator = y;
denominator = x;
end
%% Calculates the GCD
% ———— Replace this piece of the code with a while loop ———–
r = rem(numerator, denominator);
while r > 0
if r == 0
GCD = denominator;
break;
end
end
fprintf(‘The GCD of %d and %d is %d: it took calculationsn’,x,y,GCD) gcd MATLAB Answers — New Questions