Thread: Binary Euclid's Algorithm

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Registered User
    Join Date
    Sep 2004
    Posts
    2
    If your main goal here is reducing fractions, then you really don't anything more than the standard algorithm gcd(N,M) = gcd(M, N mod M). The binary version is a slight improvement over the original (based on your source) and I doubt it's really worth messing up (beyond curiosity). Consider:

    Code:
    #include <iostream.h>
    
    int GCD(int N, int M)
    {
    	if (N % M == 0)
    	{
    		return M;
    	}
    	else
    	{
    		return GCD(M, N % M);
    	}
    }
    
    int main()
    {
    	int numerator, denominator, g;
    	cout<<"Numerator: ";
    	cin>>numerator;
    	cout<<"Denominator: ";
    	cin>>denominator;
    	g = GCD(numerator, denominator);
    	cout<<endl<<numerator / g<<" / "<<denominator / g<<endl;
    	return 0;
    }
    This should do everything you need it to. Alturnatively you could write
    Code:
    (N % M == 0)?(return M):(return GCD(M, N%M))
    in place of the if-else statement
    Last edited by Kletian; 09-26-2004 at 02:44 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-13-2005, 02:53 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM