2012年9月20日

UVa 343 - What Base Is This?


#include <stdio.h>

int turn(char *s, int n) {
  int i, sum = 0;
  for (i = 0; s[i]; i++) {
    if ('0' <= s[i] && s[i] <= '9') {
      if ((s[i] - '0') >= n) return -1;
      sum = sum * n + s[i] - '0';
    } else {
      if ((s[i] - 'A' + 10) >= n) return -1;
      sum = sum * n + s[i] - 'A' + 10;
    }
  }
  return sum;
}
int main() {
  char a[200], b[200];
  while (scanf("%s%s", &a, &b) == 2) {
    int i, j, flag = 0;;
    for (i = 2; i < 37; i++) {
      if (turn(a, i) == -1) continue;
      for (j = 2; j < 37; j++)
        if (turn(a, i) == turn(b, j)) {
          printf("%s (base %d) = %s (base %d)\n", a, i, b, j);
          flag = 1;
          i = 37;
          j = 37;
        }
    }
    if (!flag) printf("%s is not equal to %s in any base 2..36\n", a, b);
  }
  return 0;
}

沒有留言:

張貼留言