fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. int main() {
  7. long long a, b;
  8. cin >> a >> b; // nieskracalny ułamek właściwy a/b
  9.  
  10. cout << "0.";
  11.  
  12. long long numerator = a;
  13. map<long long, int> seen; // reszta -> indeks cyfry
  14. vector<int> digits; // cyfry części ułamkowej
  15.  
  16. int index = 0;
  17. int repeat_start = -1;
  18.  
  19. while (numerator != 0) {
  20. if (seen.count(numerator)) {
  21. repeat_start = seen[numerator];
  22. break;
  23. }
  24. seen[numerator] = index;
  25.  
  26. numerator *= 2;
  27. if (numerator >= b) {
  28. digits.push_back(1);
  29. numerator -= b;
  30. } else {
  31. digits.push_back(0);
  32. }
  33.  
  34. index++;
  35. }
  36.  
  37. // wypisywanie rozwinięcia
  38. if (repeat_start == -1) {
  39. // brak okresu
  40. for (int d : digits) cout << d;
  41. } else {
  42. // część nieokresowa
  43. for (int i = 0; i < repeat_start; i++)
  44. cout << digits[i];
  45.  
  46. cout << "(";
  47.  
  48. // część okresowa
  49. for (int i = repeat_start; i < digits.size(); i++)
  50. cout << digits[i];
  51.  
  52. cout << ")";
  53. }
  54.  
  55. cout << endl;
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5256KB
stdin
1 3
stdout
0.(01)