//终极解决方案,参考了沙发的思路,感谢
#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;
}
void EgyptFraction(int m, int n, int k)
{
int i,t,low,high;
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
{
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;
EgyptFraction(m*t-n,n*t,k-1);
}
}
}
int main(void)
{
int i,m,n;
while (1)
{
printf("Please enter a proper fraction(a/b):");
scanf("%d/%d",&m,&n);
if (m==0)
break;
if (m>=n || 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;
}
#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;
}
void EgyptFraction(int m, int n, int k)
{
int i,t,low,high;
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
{
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;
EgyptFraction(m*t-n,n*t,k-1);
}
}
}
int main(void)
{
int i,m,n;
while (1)
{
printf("Please enter a proper fraction(a/b):");
scanf("%d/%d",&m,&n);
if (m==0)
break;
if (m>=n || 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;
}