Today we still talk about greedy algorithms. The title is: A true fraction is expressed as a number of Egyptian fractions. What is the Egyptian score? For example: 1/2 This is the Egyptian score, which is the fraction of the molecule 1. For example: 7/8=1/2+1/3+1/24.
So how do we achieve this?
Because it is an addition operation, we do this by "splitting" an item.
1. Find the largest Egyptian score, making f>1/n.
2. Output 1/n.
3.f=f-1/n.
4. If f is an Egyptian score, finish, or continue to the first step.
However, it is important to note that high-level languages do not support fractional operations, so we can only enter the numerator and denominator separately for fractions. The set molecule is a, the denominator is B. Then the b/a is C and the remainder is k,b=a*c+k. Then b/a=c+k/a, and K<a, then k/a<1, so b/a<c+1, make C+1=d, then a/b>1/d, so we find the above said N.
Second, a/b-1/d= (ad-b)/BD, so the values of a,d,b are computed separately, and then the operations are performed on them.
Finally, when a=1, we are done. It can also be a!=1, but A and b are multiples, which is also possible.
Code: The main function is not affixed.
int fz,fm,n;scanf ("%d%d", &FZ,&FM),//input numerator and denominator printf ("%d/%d=", FZ,FM), if (FZ>FM) {printf ("ERROR");} else if ( (fm%fz==0) | | Fz==1) {printf ("%d/%d", FZ,FM);} Else{while (fz!=1) {n=fm/fz+1;printf ("1/%d+", N), Fz=fz*n-fm;fm=fm*n;if (fz==1) {printf ("1/%d", FM);} if ((fz>1) && (fm%fz==0)) {printf ("1/%d", FM/FZ); fz=1;//used to End the Loop}}}
Basis of greedy algorithm (II.)