Advertisement
dimipan80

6.10Loops_EuclideanAlgorithm

Mar 24th, 2014
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. // Write a program that calculates the greatest common divisor (GCD) of given two integers a and b. Use the Euclidean algorithm (find it in Internet).
  2.  
  3. namespace _17.CalculateGCD
  4. {
  5.     using System;
  6.  
  7.     public class EuclideanAlgorithm
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             checked
  12.             {
  13.                 Console.Write("Enter a Integer number: ");
  14.                 int firstNum = int.Parse(Console.ReadLine());
  15.                 int secondNum;
  16.                 do
  17.                 {
  18.                     Console.Write("Enter other Integer number, different from the First: ");
  19.                 }
  20.                 while (!int.TryParse(Console.ReadLine(), out secondNum) || secondNum == firstNum);
  21.  
  22.                 int numA = Math.Abs(firstNum);
  23.                 int numB = Math.Abs(secondNum);
  24.                 if (numB > numA)
  25.                 {
  26.                     int numC = numA;
  27.                     numA = numB;
  28.                     numB = numC;
  29.                 }
  30.  
  31.                 while (numB > 0)
  32.                 {
  33.                     int remainder = numA % numB;
  34.                     numA = numB;
  35.                     numB = remainder;
  36.                 }                
  37.  
  38.                 int gcd = numA;
  39.                 Console.WriteLine("The Greatest Common Divisor of ({0}, {1}) is: {2} !", firstNum, secondNum, gcd);
  40.             }
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement