/* Factoring.c */
/*****************************************************************************/
/*                                                                           */
/*    Out Of Phase:  Digital Music Synthesis on General Purpose Computers    */
/*    Copyright (C) 1994  Thomas R. Lawrence                                 */
/*                                                                           */
/*    This program is free software; you can redistribute it and/or modify   */
/*    it under the terms of the GNU General Public License as published by   */
/*    the Free Software Foundation; either version 2 of the License, or      */
/*    (at your option) any later version.                                    */
/*                                                                           */
/*    This program is distributed in the hope that it will be useful,        */
/*    but WITHOUT ANY WARRANTY; without even the implied warranty of         */
/*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          */
/*    GNU General Public License for more details.                           */
/*                                                                           */
/*    You should have received a copy of the GNU General Public License      */
/*    along with this program; if not, write to the Free Software            */
/*    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.              */
/*                                                                           */
/*    Thomas R. Lawrence can be reached at tomlaw@world.std.com.             */
/*                                                                           */
/*****************************************************************************/

#include "MiscInfo.h"
#include "Audit.h"
#include "Debug.h"
#include "Definitions.h"

#include "Factoring.h"


/* find the common factors of two numbers, using Euclid's algorithm.  the product */
/* of the common factors is returned (i.e. greatest common factor). */
unsigned long					FindCommonFactors(unsigned long Left, unsigned long Right)
	{
		unsigned long				A;
		unsigned long				Am1;

		/* normalize:  gcd(a,b) = gcd(a,-b); gcd(a,b) = gcd(b,a) */
		if (Left < 0)
			{
				Left = - Left;
			}
		if (Right < 0)
			{
				Right = - Right;
			}
		if (Right == 0)
			{
				Right = Left;
				Left = 0;
			}
		ERROR(Right == 0,PRERR(ForceAbort,"FindCommonFactors:  both factors are zero"));

		/* initialize recurrence variables */
		Am1 = Left;
		A = Right;

		/* loop until a is divisible by previous a */
		while ((Am1 % A) != 0) /* not A divides Am1 */
			{
				unsigned long				T;

				T = A;
				A = Am1 % T;
				Am1 = T;
			}

		return A;
	}
