Basis of greedy algorithm (II.)

Source: Internet
Author: User

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.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.