Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# find the greatest common divisor

Tags:

c#

math

"The greatest common divisor of two integers is the largest integer that evenly divides each of the two numbers. Write method Gcd that returns the greatest common divisor of two integers. Incorporate the method into an app that reads two values from the user and displays the result."

(this is not homework, just an exercise in the book I'm using)

can you help me solve this? Here's what I've got so far.

(edit - I can submit the two numbers but it won't calculate the Gcd for me)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;  namespace Greatest_Common_Divisor { class Program {      static int GetNum(string text)     {         bool IsItANumber = false;         int x = 0;         Console.WriteLine(text);          do         {             IsItANumber = int.TryParse(Console.ReadLine(), out x);          } while (!IsItANumber);          return x;     }     static void Main(string[] args)     {         string text = "enter a number";         int x = GetNum(text);         text = "enter a second number";         int y = GetNum(text);           int z = GCD(x, y);         Console.WriteLine(z);     }      private static int GCD(int x, int y)     {         int v = 0;         int n = 0;          v = GetGreatestDivisor(x, y);           return v;      }      static int GetGreatestDivisor(int m, int h)         {              do             {                 for (int i = m; i <= 1; i--)                        if (m%i == 0 && h%i == 0)                     {                         int x = 0;                         x = i;                          return x;                     }             } while (true);             return m;         }    } } 
like image 745
user2723261 Avatar asked Aug 30 '13 21:08

user2723261


2 Answers

Here's an implementation of the Euclidean algorithm that returns the greatest common divisor without performing any heap allocation.

You can substitute ulong for uint if needed. An unsigned type is used, as the technique does not work for signed values. If you know your a and b values are not negative, you can use long or int instead.

private static ulong GCD(ulong a, ulong b) {     while (a != 0 && b != 0)     {         if (a > b)             a %= b;         else             b %= a;     }      return a | b; } 

This method is used in my metadata-extractor library, where it has associated unit tests.

like image 159
Drew Noakes Avatar answered Oct 06 '22 08:10

Drew Noakes


Using LINQ's Aggregate method:

static int GCD(int[] numbers) {     return numbers.Aggregate(GCD); }  static int GCD(int a, int b) {     return b == 0 ? a : GCD(b, a % b); } 

Note: answer above borrowed from accepted answer to Greatest Common Divisor from a set of more than 2 integers.

like image 26
Karl Anderson Avatar answered Oct 06 '22 10:10

Karl Anderson