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>
#MAX_WORD_LENGTH 30 // don't think the number could get so long
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";
/* "OSR43" was added to show that the letters of alpha
are NOT in alphabetical order */
char *word=calloc(MAX_WORD_LENGTH30,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",strrev(word));
}
return 0;
}
This code's working fine but I need to speed it up as much as possible. How do I do it?
EDIT:
I forgot to add strrev()
to reverse the result string, edited now.