Skip to content

Instantly share code, notes, and snippets.

@rafaelmv
Created August 24, 2017 14:59
Show Gist options
  • Save rafaelmv/54e012236731a8f4412ea9c219b1f290 to your computer and use it in GitHub Desktop.
Save rafaelmv/54e012236731a8f4412ea9c219b1f290 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <utility>
std::pair<int, int> getFraction(int a[], int size)
{
int n = 1;
int d = a[size-1];
for(int i = size - 2; i >= 0; i--)
{
int nextd = d*a[i] + n;
n = d;
d = nextd;
}
// When we are done, d is the numerator and n is the denominator.
return std::make_pair(d, n);
}
int main()
{
int a[] = {4, 2, 6, 7};
int size = sizeof(a)/sizeof(a[0]);
std::pair<int, int> f = getFraction(a, size);
std::cout
<< "Numerator: " << f.first
<< ", Denominator: " << f.second << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment