Find GCD of two numbers | MATLAB Tutorial
by SAURAB S
Finding GCD of two numbers
What is Greatest Common Divisor (GCD)?
- Greatest common divisor is also known by the name HCF (Highest Common Factor).
- It is the largest positive integer that divides each of the integers.
- For example, the HCF of 6 and 12 is 6.
Also, the HCF of 8 and 12 is 4.
The HCF of 10 and 30 is 10.
HCF of 12 and 76 is 4.
x1=input('Enter number 1 :'); x2=input('Enter number 2 :'); a=max(x1,x2); for i=1:a if mod(x1,i)==0 && mod(x2,i)==0 GCD=i; end end fprintf('HCF of %d and %d is %d',x1,x2,GCD) fprintf('\n')
- The HCF of two or more integers is the largest positive integer that divides each of the integers.
- Two numbers are then asked to be entered by the user. Then these two numbers are stored in two variables. Let the two variables be x1 and x2. Also, we keep a variable ‘GCD’.
- A for loop is used where a variable ‘i’ tends from 0 to max(x1,x2).
- Inside for loop the numbers x1 and x2 are then divided by ‘i’ in each loop. Whenever x1 and x2 are exactly divisible by ‘i’ then the value of gcd is set to ‘i’.
- After the for loop has finished being executed, the gcd will have the HCF of two numbers.
The following are the output for various numbers inputted
- 6 and 12
- 8 and 12
- 10 and 30
- 12 and 76