SHARE
TWEET

Untitled

a guest Oct 13th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. convert
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <strings.h>
  6. #include "long_int.h"
  7.  
  8. #define MAX_STR_LEN 1001
  9.  
  10. int ch2digit (char c)
  11. {
  12.     if (c >= '0' && c <= '9')
  13.         return c - '0';
  14.     else if (c >= 'A' && c <= 'Z')
  15.         return c - 'A' + 10;
  16.     else
  17.         return -1;
  18. }
  19.  
  20. char digit2ch (int d)
  21. {
  22.     if (d >= 0 && d <= 9)
  23.         return '0' + d;
  24.     else if (d >= 10 && d <= 35)
  25.         return 'A' + d - 10;
  26. }
  27.  
  28. void convert (const LongInt* a, LongInt* x)
  29. {
  30.     int p = a->radix;
  31.     int q = x->radix;
  32.     int k = a->num_digits - 1;
  33.  
  34.     LongInt y = { q };
  35.     init_LongInt(x, a->digits[0]);
  36.     init_LongInt(&y, 1);
  37.  
  38.     LongInt z = { q };
  39.     int i;
  40.     for (i = 1; i <= k; i++) {
  41.         // y = p^{i-1}, x = a[0] + a[1]*p + a[2]*p^2 + ... + a[i-1]*p^{i-1}
  42.         multiply_LongInt_int(&y, p);
  43.         copy_LongInt(&z, &y);
  44.         multiply_LongInt_int(&z, a->digits[i]);
  45.         add_LongInt(x, &z);
  46.         // y = p^i, x = a[0] + a[1]*p + a[2]*p^2 + ... + a[i]*p^i
  47.     }
  48.     // y = p^k, x = a[0] + a[1]*p + a[2]*p^2 + ... + a[k]*p^k
  49. }
  50.  
  51. int main ()
  52. {
  53.     FILE* fin = fopen("input.txt", "r");
  54.     FILE* fout = fopen("output.txt", "w");
  55.  
  56.     // Input data
  57.     int p, q;
  58.     char s[MAX_STR_LEN];
  59.     fscanf(fin, "%d %d\n", &p, &q);
  60.     fgets(s, MAX_STR_LEN, fin);
  61.     int len = strlen(s);
  62.     if (s[len - 1] == '\n')
  63.         len--;
  64.  
  65.     // Initialize a long number
  66.     LongInt a = { p };
  67.     a.num_digits = len;
  68.     int i;
  69.     for (i = 0; i < len; i++)
  70.         a.digits[len - 1 - i] = ch2digit(s[i]);
  71.  
  72.     // Convert the long number to another radix
  73.     LongInt b = { q };
  74.     convert(&a, &b);
  75.  
  76.     // Output data
  77.     for (i = b.num_digits - 1; i >= 0; i--) {
  78.         fprintf(fout, "%c", digit2ch(b.digits[i]));
  79.     }
  80.  
  81.     fclose(fin);
  82.     fclose(fout);
  83.  
  84.     return 0;
  85. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top