2013年8月25日

UVa 275 - Expanding Fractions

#include <stdio.h>
 
int main() {
  int n, m;
  while (scanf("%d%d", &n, &m) && m) {
    int len, ans[3333] = {}, rec[3333] = {};
    for (len = 1; ; len++) {
      ans[len - 1] = n / m;
      n = n % m;
      if (rec[n]) {
        putchar('.');
        int i;
        for (i = 1; i < rec[n]; i++) {
          printf("%d", ans[i]);
        }
        int cycle = len - rec[n];
        if (cycle == 1 && ans[rec[n]] == 0) {
          puts("\nThis expansion terminates.");
        } else {
          for (i = rec[n]; i < rec[n] + cycle; i++) {
            printf("%d%s", ans[i], (i % 50) == 49 && (i != rec[n] + cycle - 1) ? "\n" : "");
          }
          printf("\nThe last %d digits repeat forever.\n", cycle);
        }
        puts("");
        break;
      }
      rec[n] = len;
      n = n * 10;
    }
  }
  return 0;
}

沒有留言:

張貼留言