File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments