-
Notifications
You must be signed in to change notification settings - Fork 325
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #606 from Asvenomdc/Asvenomdc-profile
Egyptian Fraction
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
#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; | ||
} |