Friday, May 12, 2017

【UVa】Expanding Fractions

Problem here

Solution

  1. #include <iostream>
  2. #include <memory.h>
  3. #include <string>
  4. using namespace std;
  5. int main(){
  6. int n, m;
  7. int len[1001];
  8. while(cin >> n >> m){
  9. if(n == 0 && m == 0)
  10. break;
  11. memset(len, -1, sizeof(len));
  12. len[n] = 0;
  13. string output = ".";
  14. while(n){
  15. n *= 10;
  16. output += (n/m) + '0';
  17. n %= m;
  18. if(len[n%m] != -1)
  19. break;
  20. len[n] = output.length()-1;
  21. }
  22. for(int i = 0; i < output.length(); i++){
  23. if(i > 0 && (i%50)==0 )
  24. cout << endl;
  25. cout << output[i];
  26. }
  27. cout << endl;
  28. if(n != 0)
  29. cout << "The last " << output.length() - len[n%m] - 1 << " digits repeat forever." << endl;
  30. else
  31. cout << "This expansion terminates." << endl;
  32. //UVa 要再output一空行
  33. //cout << endl
  34. }
  35. return 0;
  36. }

No comments:

Post a Comment