Created
July 9, 2020 12:27
-
-
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)"
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
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