ntodorova

08_GreatestCommonDivisor

Nov 19th, 2012
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.89 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 8. Write a program that calculates the greatest common divisor (GCD) of given two numbers.
  5.  * Use the Euclidean algorithm.
  6.  */
  7. class GreatestCommonDivisor
  8. {
  9.     static void Main()
  10.     {
  11.         uint a;
  12.         uint b;
  13.         uint tmp;
  14.         uint gcd;
  15.  
  16.         Console.Write("A = ");
  17.         string strA = Console.ReadLine();
  18.  
  19.         Console.Write("B = ");
  20.         string strB = Console.ReadLine();
  21.  
  22.         if (!uint.TryParse(strA, out a))
  23.         {
  24.             Console.WriteLine("Invalid number: {0}", strA);
  25.         }
  26.         else if (!uint.TryParse(strB, out b))
  27.         {
  28.             Console.WriteLine("Invalid number: {0}", strB);
  29.         }
  30.         else
  31.         {
  32.             if (a == 0 && b > 0)
  33.             {
  34.                 gcd = b;
  35.             }
  36.             else if (b == 0 && a > 0)
  37.             {
  38.                 gcd = a;
  39.             }
  40.             else if (a > 0 && b > 0)
  41.             {
  42.                 while (b > 0)
  43.                 {
  44.                     tmp = b;
  45.                     b = a % b;
  46.                     a = tmp;
  47.                 }
  48.  
  49.                 gcd = a;
  50.  
  51.                 Console.WriteLine("The GCD is {0}.", gcd);
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment