Advertisement
vlad0

Loops - Euclidean Algorithm

Dec 6th, 2012
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         bool successParse;
  8.         int enteredN;
  9.         int enteredK = 0;
  10.         int minValue, maxValue;
  11.         int firstLeft=1, newLeft=1;
  12.         int tempLeft = 1;
  13.  
  14.         do
  15.         {
  16.             Console.Write("Enter N: ");
  17.             successParse = int.TryParse(Console.ReadLine(), out enteredN);
  18.             if (successParse)
  19.             {
  20.                 Console.Write("Enter K: ");
  21.                 successParse = int.TryParse(Console.ReadLine(), out enteredK);
  22.             }
  23.  
  24.         } while (!successParse);
  25.  
  26.         if (enteredK > enteredN)
  27.         {
  28.             maxValue = enteredK;
  29.             minValue = enteredN;
  30.  
  31.         }
  32.  
  33.         else
  34.         {
  35.             minValue = enteredK;
  36.             maxValue = enteredN;
  37.         }
  38.  
  39.         if (maxValue%minValue == 0)
  40.         {
  41.             Console.WriteLine("The GCD is: {0}", minValue);
  42.             return;
  43.         }
  44.  
  45.         firstLeft = maxValue % minValue;
  46.         newLeft = minValue % firstLeft;
  47.  
  48.         while (tempLeft != 0)
  49.         {
  50.  
  51.             tempLeft = firstLeft % newLeft;
  52.             firstLeft = newLeft;
  53.             newLeft = tempLeft;
  54.         }
  55.  
  56.         Console.WriteLine("The GCD is: {0}", firstLeft);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement