C++ Program for GCD 0.of more than two (or array) numbers?

C++Server Side ProgrammingProgramming

<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 &nbsp; &nbsp;if a is 0, then &nbsp; &nbsp; &nbsp; return b &nbsp; &nbsp;end if &nbsp; &nbsp;return gcd(b mod a, a) end</pre><h3>getArrayGcd(arr, n)</h3><pre class="result notranslate">begin &nbsp; &nbsp;res := arr[0] &nbsp; &nbsp;for i in range 1 to n-1, do &nbsp; &nbsp; &nbsp; res := gcd(arr[i], res) &nbsp; &nbsp;done &nbsp; &nbsp;return res; end</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/ARnkrp" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include&lt;iostream&gt; using namespace std; int gcd(int a, int b) { &nbsp; &nbsp;if (a == 0) &nbsp; &nbsp; &nbsp; return b; &nbsp; &nbsp;return gcd(b%a, a); } int getArrayGcd(int arr[], int n) { &nbsp; &nbsp;int res = arr[0]; &nbsp; &nbsp;for(int i = 1; i &lt; n; i++) { &nbsp; &nbsp; &nbsp; res = gcd(arr[i], res); &nbsp; &nbsp;} &nbsp; &nbsp;return res; } main() { &nbsp; &nbsp;int arr[] = {4, 8, 16, 24}; &nbsp; &nbsp;int n = sizeof(arr)/sizeof(arr[0]); &nbsp; &nbsp;cout &lt;&lt; &quot;GCD of array elements: &quot; &lt;&lt; getArrayGcd(arr, n); }</pre><h2>Output</h2><pre class="result notranslate">GCD of array elements: 4</pre>
Updated on 30-Jul-2019 22:30:26