Saturday, June 19, 2021
Home coding Write a program to gcd of array.

Write a program to gcd of array.

Given a integer array , we have to find the GCD of array and print their resultant value.

So what is GCD of number?

GCD of array is to find the maximum number which divide whole array

Example:

input:2 ,4,6,8 
output:2

Logic:

we have to just find the maximum number which divide whole array.

Code-

#include<bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
	if (b == 0)
		return a;
	return gcd(b, a % b); 
	
}
int main()
{
    int arr[]={60,80,100,120,80};
    int k;
    int n=sizeof(arr)/sizeof(arr[0]);
    for(int i=0;i<n;i++)
    {
        k=gcd(arr[i],k);
    }
	cout<<k<<endl;

}

Output:

20

Time complexity:0(N)

Space Complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments