Skip to content

Instantly share code, notes, and snippets.

@sato11
Created July 9, 2020 12:27
Show Gist options
  • Save sato11/36abbaa4b43b26f01ef5d100dec321e8 to your computer and use it in GitHub Desktop.
Save sato11/36abbaa4b43b26f01ef5d100dec321e8 to your computer and use it in GitHub Desktop.
notate rational number including cyclical one. e.g. to_rational(1, 7) == "0.(142857)"
std::string to_rational(int numerator, int denominator)
{
std::string result;
int n = numerator / denominator;
result += std::to_string(n);
if (numerator % denominator == 0) return result;
result += ".";
int remainder = numerator % denominator;
std::vector<int> place, rems;
std::vector<int>::iterator it;
while ((it = std::find(rems.begin(), rems.end(), remainder)) == rems.end())
{
rems.push_back(remainder);
place.push_back(remainder * 10 / denominator);
remainder = remainder * 10 % denominator;
if (remainder == 0)
{
for (int p : place) result.push_back(p + '0');
return result;
}
}
int idx = std::distance(rems.begin(), it);
for (int i = 0; i < place.size(); ++i)
{
if (i == idx) result += "(";
result += place[i] + '0';
}
result += ")";
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment