Skip to main content
2 of 7
edited title
ForceBru
  • 455
  • 2
  • 10

Converting from base-10 to word

The following code is used to convert a base-10 number to a base-N number, where N is a length of a given alphabet that contains characters of which a base-N number can consist.

The number to convert is always increasing, like from 1 to 45789, not from 536 to 13. The resulting number may not contain zero as first digit, so I need to carry the one.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef unsigned long long ull;

void conv(ull num, const char *alpha, char *word, int base){
    while (num) {
       *(word++)=alpha[(num-1)%base];
       num=(num-1)/base;
    }
}

int main(){
   ull nu;
   const char alpha[]="abcdefghijklmnopqrstuvwxyzOSR34";
   char *word=calloc(30,sizeof(char));
   // word always contains null-terminator
   int base=(int)strlen(alpha);
   for (nu=1;nu<=1e8;++nu) {
       conv(nu,alpha,word,base);
       printf("%s\n",word);
   }
   return 0;
}

This code's working fine but I need to speed it up as much as possible. How do I do it?

ForceBru
  • 455
  • 2
  • 10