天天看點

貪心法之埃及分數

一個真分數表示為最少的埃及分數之和的形式

雖然這個代碼是這個樣子的

這個算法也是對的

但是迷迷糊糊 好像就是這樣可以算出來

像是數學題 但是沒有寫出來的感覺

// 0521.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int CommFactor(int m,int n)
{
	int r=m%n;
	while(r!=0)
	{
		m=n;
		n=r;
		r=m%n;
	}
	return n;
}

void EgyptFraction(int A,int B)
{
	int E,R;
	cout<<A<<"/"<<B<<"=";
	do
	{
		E=B/A+1;
		cout<<"1/"<<E<<"+";
		A=A*E-B;
		B=B*E;
		R=CommFactor(B,A);
		if(R>1)
		{
			A=A/R;
			B=B/R;
		}
	}while(A>1);
		cout<<"1/"<<B<<endl;
	return;
}


int main()
{
	int A;
	int B;
	cin>>A;
	cin>>B;
	EgyptFraction(A,B);

	
	return 0;
}