+ 2
Guys can anybody tell how to find the HCF/GCD of n numbers in C++?
Please help me
6 odpowiedzi
+ 21
Here is the code for n integer divisor. Just consider to put 0 as your last divisor (infinite loop terminator)
https://code.sololearn.com/cheiBr290ubx/?ref=app
+ 18
Here is a good explanation for you to start and come up with your own solution.
[https://www.programiz.com/c-programming/examples/hcf-gcd]
+ 2
bro thanks for ur help , but I want gcd of n numbers , as I know how to find gcd of 2 numbers , but its very difficult to find gcd of n numbers. So i am still waiting .
+ 1
GCD
GCD (a,b)
until b!=0 do
r<= a mod b
a<= b
b<= r
after that return 'a' and finish
FOR EXAMPLE
a=10, b=5
r<= 10mod5
r <= 0
a<= 5
b<= 0
b is 0 so it returns 'a' which is 5
GCD(10,5)=5
0
int gcd(a,b){
if(b<a) swap(a,b);
if(a==0) return b;
return gcd(b%a, a);
}
int hcf(a,b){
return a*b/gcd(a,b);
}
vector<int> a; // put elements in this
int ans = a[0];
for(int i=1; i<a.size() && ans!=1; i++){
ans = gcd(ans, a[i]);
}
cout << ans << '\n';
// time complexity : O(n*logn).
// space complexity : O(logn) for stack.