-
Notifications
You must be signed in to change notification settings - Fork 5
/
egyptfract.cpp
54 lines (47 loc) · 1.06 KB
/
egyptfract.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// C++ program to print a fraction in Egyptian Form using Greedy
// Algorithm
#include <iostream>
using namespace std;
void printEgyptian(int nr, int dr)
{
// If either numerator or denominator is 0
if (dr == 0 || nr == 0)
return;
// If numerator divides denominator, then simple division
// makes the fraction in 1/n form
if (dr%nr == 0)
{
cout << "1/" << dr/nr;
return;
}
// If denominator divides numerator, then the given number
// is not fraction
if (nr%dr == 0)
{
cout << nr/dr;
return;
}
// If numerator is more than denominator
if (nr > dr)
{
cout << nr/dr << " + ";
printEgyptian(nr%dr, dr);
return;
}
// We reach here dr > nr and dr%nr is non-zero
// Find ceiling of dr/nr and print it as first
// fraction
int n = dr/nr + 1;
cout << "1/" << n << " + ";
// Recur for remaining part
printEgyptian(nr*n-dr, dr*n);
}
// Driver Program
int main()
{
int nr = 6, dr = 14;
cout << "Egyptian Fraction Representation of "
<< nr << "/" << dr << " is\n ";
printEgyptian(nr, dr);
return 0;
}