need help

This is a discussion on need help within the C++ Programming forums, part of the General Programming Boards category; WHat is the best way to go about simplifying a fraction? I am working with 2 integers, numerator and denominator. ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    5

    need help

    WHat is the best way to go about simplifying a fraction? I am working with 2 integers, numerator and denominator. if the fraction is in the form of 0/N then it will be set to 0/1. that is easy to code. I need this function to simplify all other fractions for example 2/4 --> 1/2 or 300/1000 --> 3/10. Should I use the modulus operator somehow?

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    Find the greatest common divisor of both integers & divide.

    There are simple (inefficient) ways to do that, or you can read about
    Euclid's algorithm

  3. #3
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Heres code for finding the GCD. My school wrote this for us so using it shouldnt be to difficult. You just have to divide each of the fractions by GCD.

    Code:
    int greatestCommonDivisor(int x, int y) {
    	while (y != 0) {
    		int temp = x % y;
    		x = y;
    		y = temp;
    	}
    	return x;
    }
    So for example made a function called Simplify and in it first i called the GCD function above by passing the numerator and denomator. GCD function retuns the GCD and i divide the numerator and denominator by GCd in the simplify function.
    Hope that helps
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21