Last active
November 18, 2020 11:57
Find GCD for several numbers at once. Just a common snippet for math problems.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gcd for n numbers | |
static int gcd(int[] numbers) | |
{ | |
return numbers.Aggregate(gcd); | |
} | |
// gcd for 2 | |
static int gcd(int a, int b) | |
{ | |
return b == 0 ? a : gcd(b, a % b); | |
} | |
private HashSet<int> FindAllDivisors(List<int> arr) | |
{ | |
// Variable to find the gcd | |
// of N numbers | |
int g = arr[0]; | |
// Set to store all the common divisors | |
HashSet<int> divisors = new HashSet<int>(); | |
// Finding GCD of the given | |
// N numbers | |
for (int i = 1; i < arr.Count; i++) | |
{ | |
g = gcd(arr[i], g); | |
} | |
// Finding divisors of the HCF of n numbers | |
for (int i = 1; i * i <= g; i++) | |
{ | |
if (g % i == 0) | |
{ | |
divisors.Add(i); | |
if (g / i != i) | |
divisors.Add(g / i); | |
} | |
} | |
return divisors; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment