• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
December 08, 2022 |5.2K Views
C++ Program for GCD of more than two (or array) numbers
  Share  1 Like
Description
Discussion

In this video, we will write C++ Program for GCD of more than two (or array) numbers. 

Examples:
Input : arr[] = {1, 2, 3}
Output: 1

Input : arr[] = {2, 4, 6, 8}
Output: 2

Here we covered 3 different methods for GCD of more than two (or array) numbers in C++.

  1. Using for loop
  2. Using Modulo method
  3. Using recursion

1. Using for loop:
In this method, we will run a for loop and we will iterate over each element to find the GCD of the previous 2 elements and current elements. After the loop ends, we will have the GCD of the entire array as we calculated it in a set of 2.

2. Using the Modulo method: In this method, we will set the first number as our GCD and we will then run a while loop to iterate all the elements in the array. While iterating, if the GCD is a factor of the array element, then we will increment the index. If the GCD is not a factor, we will update the GCD to the modulo of the array element with GCD.
 
3. Using recursion:
In this method, we will have a call to recursive functions with a base case of reaching the end of an array. Here we use the inbuilt GCD function. It will return the GCD of the current element and the next element.
 

C++ program for GCD of more than two numbers: 
https://www.geeksforgeeks.org/cpp-program-for-gcd-of-more-than-two-or-array-numbers/

Read More