我的完整思路(本人只有高中毕业,都是自学的,我想做个程序员,hwdwow@163.com)
//把真分数m/n(m,m互质)k(k>2)个埃及分数,最大的一个埃及分数的分母t必然满足1/t<m/n<k/t
#include <stdio.h>
#define N 10
int g_best[N],g_temp[N],g_nParts;
int g_found;
//求最大公约数
int Gcd(int m, int n)
{
int t;
while (m>0)
{
t=n%m;
n=m;
m=t;
}
return n;
}
//把m/n分解为k个埃及分数
void EgyptFraction(int m, int n, int k)
{
int i,t,low,high;
if (n<=0 || m<=0) //溢出
return;
t=Gcd(m,n); //先约分防止在后面的分解中变得太大
m/=t;
n/=t;
if (k==1)
{
if (m==1)
{
g_temp[0]=n;
if (!g_found || (g_found && n<g_best[0]))
{
g_found=1;
for (i=0; i<g_nParts; i++)
g_best[i]=g_temp[i];
}
}
}
else
{
//第k个埃及分数分母的上下限low,high
low=n/m+1;
if (k<g_nParts && g_temp[k]+1>low)
low=g_temp[k]+1;
high = (k*n%m==0)? k*n/m-1:k*n/m;
for (t=low; t<=high; t++)
{
g_temp[k-1]=t;
// m/n-1/t后的剩余部分分解为k-1个埃及分数
EgyptFraction(m*t-n,n*t,k-1);
}
}
}
int main(void)
{
int i,m,n;
while (1)
{
printf("Please enter a proper fraction m/n (n<1000):");
scanf("%d/%d",&m,&n);
if (m==0)
break;
if (m>=n || n>=1000 || m<=0 || n<=0)
continue;
g_found=0;
g_nParts=0;
do
{
g_nParts++;
EgyptFraction(m,n,g_nParts);
}while (!g_found && g_nParts<N);
if (g_found)
{
for (i=g_nParts-1; i>0; i--)
printf("1/%d+",g_best[i]);
printf("1/%d\n",g_best[0]);
}
else
printf("Too complex!\n");
}
return 0;
}
[
本帖最后由 hwdwow 于 2009-9-10 23:32 编辑 ]