Skip to content

Commit 87dd53a

Browse files
authored
Merge pull request codewithdev#69 from sahiljethani/master
Added Greedy Algorithm For Egyptian Fraction
2 parents 41d7d78 + b89ff2a commit 87dd53a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
// Program to print a fraction in Egyptian Form using Greedy Algorithm
3+
/*
4+
Example:Egyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231
5+
Egyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156
6+
*/
7+
#include <iostream>
8+
using namespace std;
9+
10+
void printEgyptian(int num, int dnum)
11+
{
12+
if (dnum == 0 || num == 0)
13+
return;
14+
15+
if (dnum%num == 0)
16+
{
17+
cout << "1/" << dnum/num;
18+
return;
19+
}
20+
21+
if (num%dnum == 0)
22+
{
23+
cout << num/dnum;
24+
return;
25+
}
26+
27+
if (num > dnum)
28+
{
29+
cout << num/dnum << " + ";
30+
printEgyptian(num%dnum, dnum);
31+
return;
32+
}
33+
34+
int n = dnum/num + 1;
35+
cout << "1/" << n << " + ";
36+
37+
printEgyptian(num*n-dnum, dnum*n);
38+
}
39+
40+
int main()
41+
{
42+
int num = 12, dnum= 13;
43+
cout << "Egyptian Fraction Representation of "
44+
<< num << "/" << dnum << " is\n ";
45+
printEgyptian(num, dnum);
46+
return 0;
47+
}

0 commit comments

Comments
 (0)