Home

The Rational

     

Introduction

The rational is a number that is represented by two parts, a numerator and a denominator. To programmatically find this number, first get their greatest common divisor. Then, get the rational. Here is an example of finding a rational:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arithmetic
{
    public static class Exercise
    {
        public static int GreatestCommonDivisor(int a, int b)
        {
            int Remainder;

            while (b != 0)
            {
                Remainder = a % b;
                a = b;
                b = Remainder;
            }

            return a;
        }

        public static string GetRational(int a, int b)
        {
            string Result;
            int gcd = GreatestCommonDivisor(a, b);
            int Numerator, Denominator;

            Numerator = a / GreatestCommonDivisor(a, b);
            Denominator = b / GreatestCommonDivisor(a, b);
            Result = string.Format("{0}/{1}", Numerator, Denominator);
            return Result;
        }
    }

    public class Program
    {
        static int Main(string[] args)
        {
            int x, y;

            Console.WriteLine("This program allows calculating " +
				"the Greatest Common Divisor");
            Console.Write("Enter Value 1: ");
            x = int.Parse(Console.ReadLine());
            Console.Write("Enter Value 2: ");
            y = int.Parse(Console.ReadLine());

            Console.WriteLine("\nThe Greatest Common Divisor of {0} and {1} is {2}.",
                x, y, Arithmetic.GreatestCommonDivisor(x, y));
            Console.WriteLine("Rational: {0}\n", Arithmetic.GetRational(x, y));

            return 0;
        }
    }
}

Here is an example of running the program:

This program allows calculating the rational
Enter Value 1: 15
Enter Value 2: 3

The Greatest Common Divisor of 15 and 3 is 3.
Rational: 5/1

Press any key to continue . . .

Here is another example of running the program:

This program allows calculating the rational
Enter Value 1: 64
Enter Value 2: 12

The Greatest Common Divisor of 64 and 12 is 4.
Rational: 16/3

Press any key to continue . . .
 

Here is one more example of running the program:

This program allows calculating the rational
Enter Value 1: 84024
Enter Value 2: 128

The Greatest Common Divisor of 84024 and 128 is 8.
Rational: 10503/16

Press any key to continue . . .
 
 

Home Copyright © 2009-2011 FunctionX