Reputation:
I have to write a program which calculates the gcd with three numbers using the euclid algorithms
I have already written the program with 2 numbers which works very well but I have no idea how can I do the same with three numbers (The big problem is it should be with the euclid algorithms)
if (z1==z2)
{
Console.WriteLine($"The gcd of two number is {z1}");
}
else {
do
{
r = z1 % z2;
gcd = z1;
z1 = z2;
z2 = r;
} while (r != 0);
Console.WriteLine($"The gcd of two number is {gcd}");
Upvotes: 2
Views: 1829
Reputation: 37020
You can write a method that gets the GCD from 2 numbers, and after calling it with 2 numbers, continue to call it with that result and the next number until there are no more numbers left.
For example, we can write a method to get the GCD of two numbers (borrowed from this site):
public static int GCD(int first, int second)
{
while (first != 0 && second != 0)
{
if (first > second) first %= second;
else second %= first;
}
return first == 0 ? second : first;
}
Then we can write another method that takes in a variable number of int
arguments (using a params
array), which gets the result of the first 2 numbers, and then continues to update that value by passing it along with the next number to our GCD method:
public static int GCD(params int[] numbers)
{
// Do some argument validation and return 0 or throw an exception
if (numbers == null || numbers.Length == 0) return 0;
// Start with the result being just the first number
var result = numbers[0];
// Then get the GCD of the result and the next number
// and store that back in the result variable
for(int i = 1; i < numbers.Length;i++)
{
result = GCD(result, numbers[i]);
}
return result;
}
Now we can call the method with as many numbers as we like:
Console.WriteLine(GCD(9, 18, 27)); // Output: 9
Console.WriteLine(GCD(4, 8)); // Output: 4
Console.WriteLine(GCD(25, 15, 100, 30, 9000)); // Output: 5
Upvotes: 4