

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program for GCD 0.of more than two (or array) numbers?
<p>Here we will see how we can get the gcd of more than two numbers. Finding gcd of two numbers are easy. When we want to find gcd of more than two numbers, we have to follow the associativity rule of gcd. For example, if we want to find gcd of {w, x, y, z}, then it will be {gcd(w,x), y, z}, then {gcd(gcd(w,x), y), z}, and finally {gcd(gcd(gcd(w,x), y), z)}. Using array it can be done very easily.</p><h2>Algorithm</h2><h3>gcd(a, b)</h3><pre class="result notranslate">begin if a is 0, then return b end if return gcd(b mod a, a) end</pre><h3>getArrayGcd(arr, n)</h3><pre class="result notranslate">begin res := arr[0] for i in range 1 to n-1, do res := gcd(arr[i], res) done return res; end</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/ARnkrp" rel="nofollow" target="_blank"> Live Demo</a></p><pre class="prettyprint notranslate">#include<iostream> using namespace std; int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } int getArrayGcd(int arr[], int n) { int res = arr[0]; for(int i = 1; i < n; i++) { res = gcd(arr[i], res); } return res; } main() { int arr[] = {4, 8, 16, 24}; int n = sizeof(arr)/sizeof(arr[0]); cout << "GCD of array elements: " << getArrayGcd(arr, n); }</pre><h2>Output</h2><pre class="result notranslate">GCD of array elements: 4</pre>
- Related Questions & Answers
- C++ Program for GCD of more than two (or array) numbers?
- Python Program for GCD of more than two (or array) numbers
- Java Program for GCD of more than two (or array) numbers
- GCD of more than two (or array) numbers in Python Program
- Finding LCM of more than two (or array) numbers without using GCD in C++
- Java program to find the GCD or HCF of two numbers
- Program to find GCD or HCF of two numbers in C++
- Find GCD of two numbers
- Java Program to Find GCD of two Numbers
- Program to compute gcd of two numbers recursively in Python
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- GCD and LCM of two numbers in Java
- GCD of an array of numbers in java
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- C# program to find Union of two or more Dictionaries
Advertisements