2020-05-28 06:51:39 +08:00
|
|
|
/**
|
|
|
|
* @file
|
|
|
|
* @brief This program aims at calculating the GCD of n numbers by division
|
|
|
|
* method
|
|
|
|
*
|
2020-05-28 06:55:09 +08:00
|
|
|
* @see gcd_iterative_euclidean.cpp, gcd_recursive_euclidean.cpp
|
2020-05-28 06:51:39 +08:00
|
|
|
*/
|
2017-12-24 01:30:49 +08:00
|
|
|
#include <iostream>
|
2020-05-26 11:13:26 +08:00
|
|
|
|
2020-05-28 06:51:39 +08:00
|
|
|
/** Compute GCD using division algorithm
|
|
|
|
*
|
|
|
|
* @param[in] a array of integers to compute GCD for
|
|
|
|
* @param[in] n number of integers in array `a`
|
|
|
|
*/
|
|
|
|
int gcd(int *a, int n) {
|
|
|
|
int j = 1; // to access all elements of the array starting from 1
|
|
|
|
int gcd = a[0];
|
|
|
|
while (j < n) {
|
|
|
|
if (a[j] % gcd == 0) // value of gcd is as needed so far
|
|
|
|
j++; // so we check for next element
|
|
|
|
else
|
|
|
|
gcd = a[j] % gcd; // calculating GCD by division method
|
|
|
|
}
|
|
|
|
return gcd;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Main function */
|
2020-05-26 11:13:26 +08:00
|
|
|
int main() {
|
|
|
|
int n;
|
|
|
|
std::cout << "Enter value of n:" << std::endl;
|
|
|
|
std::cin >> n;
|
2020-05-26 11:22:26 +08:00
|
|
|
int *a = new int[n];
|
2020-05-28 06:51:39 +08:00
|
|
|
int i;
|
2020-05-26 11:13:26 +08:00
|
|
|
std::cout << "Enter the n numbers:" << std::endl;
|
|
|
|
for (i = 0; i < n; i++) std::cin >> a[i];
|
2020-05-28 06:51:39 +08:00
|
|
|
|
|
|
|
std::cout << "GCD of entered n numbers:" << gcd(a, n) << std::endl;
|
|
|
|
|
2020-05-26 11:22:26 +08:00
|
|
|
delete[] a;
|
2020-05-26 11:13:26 +08:00
|
|
|
return 0;
|
2017-12-24 01:30:49 +08:00
|
|
|
}
|