C Programming – HackerRank Solution | GCD of an Array 1 |

(HackerRank) Write a Modular C Programming code to solve the GCD of an Array 1, Given an array of ‘N’ integers compute the GCD of an array. GCD of an array is computed as follows:

Given an array of ‘N’ integers compute GCD of an array. GCD of an array is computed as follows:

GCD(a[])=GCD(a[0], a[1], a[2], …. a[n-1])

Input Format

First Line ‘N’ number of array elements.

Next Line contains ‘N’ number of array elements.

Constraints

N>0 and N<=10^5

0

Output Format

Output the GCD in a single line

Sample Input 0

-1

Sample Output 0

Invalid

Sample Input 1

5
3 6 9 12 15

Sample Output 1

3

Explanation 1

clearly the GCD is 3, since 3 is the maximum number that divides every number in an array

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings

 

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main() {
    int n,max=1,i,j,status;
    scanf("%d",&n);
    
    if(n>0)
    {
        int array[n];
        for(i=0;i<n;i++)
            scanf("%d",&array[i]);
        int min=array[0];
        for(i=0;i<n;i++) { if(min>array[i])
                min=array[i];
        }
        for(i=1;i<=min;i++)
        {
            status=1;
            for(j=0;j<n;j++)
            {
                if(array[j]%i!=0)
                {
                    status=0;
                    break;
                }
            }
            if(status==1)
                max=i;
        }
        printf("%d",max);
    }
    else{
        printf("Invalid");
    }
    return 0;
}

OUTPUT

Congratulations, you passed the sample test case.

Click the Submit Code button to run your code against all the test cases.

Input (stdin)

-1
Your Output (stdout)

Invalid
Expected Output

Invalid

 

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University

Leave a Comment