Skip to content

Commit a4c4dff

Browse files
authored
Create HCF_using_Euclidean_algorithm.cpp
This program computes the HCF of given two numbers using Euclidean algorithm which takes logarithmic time complexity.
1 parent 9bf1fc9 commit a4c4dff

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//C++ program to compute HCF/GCD of two numbers using Euclidean algorithm
2+
//This algorithm finds HCF of two numbers in logarithmic time complexity
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
// Function to compute HCF/GCD
8+
9+
int Compute_HCF(int a, int b){
10+
// Loop as long as both the numbers are greater than zero
11+
while(a>0 && b>0){
12+
// If a is greater than b then modularise a with b
13+
if(a>b){
14+
a = a%b;
15+
}
16+
// Otherwise modularise b with a
17+
else{
18+
b = b%a;
19+
}
20+
}
21+
// After the termination of loop, the non zero number will be the HCF/GCD
22+
if(a==0) return b;
23+
return a;
24+
}
25+
26+
27+
int main(){
28+
// Input two numbers
29+
int a,b;
30+
cin >> a >> b;
31+
// Call Compute_HCF function to evaluate HCF
32+
cout << Compute_HCF(a,b) ;
33+
}
34+
35+
/*
36+
Time complexity = O(log(min(a,b)))
37+
Space complexity = O(1)
38+
*/

0 commit comments

Comments
 (0)