This program aims at calculating the GCD of n numbers.
More...
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
This program aims at calculating the GCD of n numbers.
The GCD of n numbers can be calculated by repeatedly calculating the GCDs of pairs of numbers i.e. \(\gcd(a, b, c)\) = \(\gcd(\gcd(a, b), c)\) Euclidean algorithm helps calculate the GCD of each pair of numbers efficiently
- See also
- gcd_iterative_euclidean.cpp, gcd_recursive_euclidean.cpp
◆ check_all_zeros()
| bool math::gcd_of_n_numbers::check_all_zeros |
( |
const std::array< int, n > & | a | ) |
|
Function to check if all elements in the array are 0.
- Parameters
-
- Returns
- 'True' if all elements are 0
-
'False' if not all elements are 0
53 {
54
55 return std::all_of(a.begin(), a.end(), [](
int x) { return x == 0; });
56}
◆ gcd()
| int math::gcd_of_n_numbers::gcd |
( |
const std::array< int, n > & | a | ) |
|
Main program to compute GCD using the Euclidean algorithm.
- Parameters
-
| a | Array of integers to compute GCD for |
- Returns
- GCD of the numbers in the array or std::nullopt if undefined
64 {
65
67 return -1;
68 }
69
70
71 int result = std::abs(a[0]);
74 if (result == 1) {
75 break;
76 }
77 }
79}
uint64_t result(uint64_t n)
Definition fibonacci_sum.cpp:76
int gcd_two(int x, int y)
Function to compute GCD of 2 numbers x and y.
Definition gcd_of_n_numbers.cpp:35
bool check_all_zeros(const std::array< int, n > &a)
Function to check if all elements in the array are 0.
Definition gcd_of_n_numbers.cpp:53
◆ gcd_two()
| int math::gcd_of_n_numbers::gcd_two |
( |
int | x, |
|
|
int | y ) |
Function to compute GCD of 2 numbers x and y.
- Parameters
-
| x | First number |
| y | Second number |
- Returns
- GCD of x and y via recursion
35 {
36
37 if (y == 0) {
38 return x;
39 }
40 if (x == 0) {
41 return y;
42 }
44}
◆ main()
Main function.
- Returns
- 0 on exit
111 {
113 return 0;
114}
static void test()
Self-test implementation.
Definition gcd_of_n_numbers.cpp:87
◆ test()
Self-test implementation.
- Returns
- void
87 {
96
97 assert(math::gcd_of_n_numbers::gcd(array_1) == -1);
98 assert(math::gcd_of_n_numbers::gcd(array_2) == 1);
99 assert(math::gcd_of_n_numbers::gcd(array_3) == 2);
100 assert(math::gcd_of_n_numbers::gcd(array_4) == 6);
101 assert(math::gcd_of_n_numbers::gcd(array_5) == 100);
102 assert(math::gcd_of_n_numbers::gcd(array_6) == -1);
103 assert(math::gcd_of_n_numbers::gcd(array_7) == 3450);
104 assert(math::gcd_of_n_numbers::gcd(array_8) == 1);
105}