きったんの頭

/*
 * pe16.c
 * https://mind.kittttttan.info/c/pe16
 */
#include <stdio.h>
#include <string.h>

enum { MAX_ORDER = 512 };

/**
 * sum of digits for 2^n
 * @param[in] n power of 2
 */
void pe16(int n) {
  static char bits[MAX_ORDER];
  int i;
  int m = n;
  int sum = 0;
  
  /* init: set 0...01 */
  memset(bits, 0, MAX_ORDER);
  bits[0] = 1;

  if (n > 0) {
    while (m--) {
      /* x2 */
      for (i = 0; i < MAX_ORDER; ++i) {
        bits[i] <<= 1;
      }
      
      /* ceil */
      for (i = 0; i < MAX_ORDER - 1; ++i) {
        while (bits[i] > 9) {
          ++bits[i + 1];
          bits[i] -= 10;
        }
      }

      /* check overflow */
      if (bits[MAX_ORDER - 1] > 9) {
        fprintf(stderr, "overflow\n");
        return;
      }
    }
  }
  
  i = MAX_ORDER;
  /* ignore following zeros */
  while (i--) {
    if (bits[i]) break;
  }
  ++i;

  /* print for debug */
  printf("2 ^ %d = ", n);
  while (i--) {
    printf("%c", bits[i] + '0');
    
    sum += bits[i];
  }
  printf("\n");
  
  printf("sum of digits = %d\n", sum);
}

int main() {
  int n;

  puts("Probrem 16:");
  while (1) {
    if (scanf("%d", &n) != 1) {
      scanf("%*s");
      puts("Input Number.");
    } else {
      if (!n) {
        break;
      }
      pe16(n);
    }
  }

  return 0;
}