In VB.NET or C#, I would like to be able calculate the Greatest Common Divisor (GCD) of one or more values, dynamically, and without using recursive methodology.
I took as a guideline this solution in C# to calculate the GCD of two values. Now, I would like to adapt that solution to be able calculate an undetermined amount of values (one or more values that are contained in a array of values passed to the function below)...
This is what I did by the moment:
VB.NET (original code):
<DebuggerStepperBoundary>
Private Shared Function InternalGetGreatestCommonDivisor(ParamArray values As Integer()) As Integer
' Calculate GCD for 2 or more values...
If (values.Length > 1) Then
Do While Not values.Contains(0)
For Each value As Integer In values
Dim firstMaxValue As Integer = values.Max()
Dim secondMaxValue As Integer = values.OrderByDescending(Function(int As Integer) int)(1)
values(values.ToList.IndexOf(firstMaxValue)) = (firstMaxValue Mod secondMaxValue)
Next value
Loop
Return If(values.Contains(0), values.Max(), values.Min())
Else ' Calculate GCD for a single value...
Return ...
End If
End Function
C# (online code conversion, I didn't tested it at all):
[DebuggerStepperBoundary]
private static int InternalGetGreatestCommonDivisor(params int[] values)
{
// Calculate GCD for 2 or more values...
if (values.Length > 1)
{
while (!values.Contains(0))
{
foreach (int value in values)
{
int firstMaxValue = values.Max();
int secondMaxValue = values.OrderByDescending((int @int) => @int).ElementAtOrDefault(1);
values[values.ToList().IndexOf(firstMaxValue)] = (firstMaxValue % secondMaxValue);
}
}
return (values.Contains(0) ? values.Max() : values.Min());
}
else // Calculate GCD for a single value...
{
return ...;
}
I'm aware that the type conversion to List would affect overall performance for a large amount of values, but the most priority thing is to make this algorithm work as expected, and finally optimize/refactorize it.
My adaptation works as expected for some combinations of values, but it does not work for anothers. For example in this online GCD calculator, if we put these values: {1920, 1080, 5000, 1000, 6800, 5555} in theory the GCD is 5, or at least that is the GCD calculated by that online service, but my algorithm returns 15.