模拟除法,当出现余数第二次相同时可以记为一个循环节。
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 | #include<iostream> #include<string> #include<map> #include<cmath> #include<cstring> #include<typeinfo> using namespace std; void solve(int a, int b) { int OA = a; string strInt = to_string(a / b); a %= b; a *= 10; string strDec = ""; map<int, int> dict; while (dict.count(a) == 0) { dict[a] = strDec.size(); strDec += to_string(a / b); a %= b; a *= 10; } string strDec1 = strDec.substr(0, dict[a]); string strDec2 = strDec.substr(dict[a]); string strDec3 = ""; if (strDec2.size() > 50) { strDec3 = '(' + strDec2.substr(0, 50) + "...)"; } else { strDec3 = '(' + strDec2 + ")"; } cout << OA << "/" << b << " = " << strInt << "." << strDec1 << strDec3 << '\n'; cout << " " << strDec2.size() << " = number of digits in repeating cycle" << '\n'; cout << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); int a, b; while (cin >> a >> b)solve(a, b); } |