Skip to content

Instantly share code, notes, and snippets.

@jcarrano
Created June 19, 2017 05:25
Show Gist options
  • Save jcarrano/3a374bf2a5c75c31df62b7ff7c7bfd30 to your computer and use it in GitHub Desktop.
Save jcarrano/3a374bf2a5c75c31df62b7ff7c7bfd30 to your computer and use it in GitHub Desktop.
Two programs to convert an integer to Roman Numerals (written somewhere in 2010)
#include <stdio.h>
#include <stdlib.h>
#define MAXROMAN 3999 /*MMMCMXCIX*/
#define DIEZ 2
#define CINCO 1
#define UNO 0
const char seq[4][3]={ {'M', '?' , '?' }, { 'C' , 'D', 'M'}, { 'X' , 'L', 'C'}, {'I', 'V', 'X'} };
int toroman(char dest[], int n);
int main(int argc, char *argv[]){
int num;
char roman[20];
if(argc==2 && (num=atoi(argv[1])) ){
if(!toroman(roman ,num)){
printf("%s\n", roman);
} else {
printf("error\n");
}
} else {
printf("tenes que decirme que numeros queres que convierta\n");
}
return 0;
}
int toroman(char dest[], int n){
int temp, mod=1000, i=0, dest_i=0;
if(n>MAXROMAN){
return 1;
}
while(mod){
if(!(temp=(n/mod))){
/*nada*/
}else if(temp!=4&&temp!=9){
if(temp>=5){
dest[dest_i++]=seq[i][CINCO];
temp-=5;
}
while(temp){
dest[dest_i++]=seq[i][UNO];
temp--;
}
}else {
dest[dest_i++]=seq[i][UNO];
if(temp==4){
dest[dest_i++]=seq[i][CINCO];
}else{
dest[dest_i++]=seq[i][DIEZ];
}
}
i++;
n-=(n/mod)*mod;
mod=mod/10;
}
dest[dest_i]='\0';
return 0;
}
/*hay que hacer código tonto y poner la inteligancia en los datos*/
#include <stdio.h>
#include <stdlib.h>
#define MAXROMAN 3999 /*MMMCMXCIX*/
#define MASK 0x03
const char seq[4][3]={
{'M', '?' , '?' },
{ 'C' , 'D', 'M'},
{ 'X' , 'L', 'C'},
{'I', 'V', 'X'} };
/*las reglas son cuatro campos de dos bits que indican como se escribe casa numeros
pero estan en el sentido inverso*/
const char reglas[10]= { /* 01=I, 10=V, 11=X */
0, /*se escribe en sentido inverso*/
0x1, /* I */
0x5, /* II */
0x15, /* III */
0x9, /* VI = 4*/
0x2, /* V = 5 */
0x6, /* IV = 6 */
0x16, /* IIV =7 */
0x56, /* IIIV =8 */
0xd, /* XI = 9*/};
int toroman(char dest[], int n);
int main(int argc, char *argv[]){
int num;
char roman[20];
if(argc==2 && (num=atoi(argv[1])) ){
if(!toroman(roman ,num)){
printf("%s\n", roman);
} else {
printf("error\n");
}
} else {
printf("tenes que decirme que numeros queres que convierta\n");
}
return 0;
}
int toroman(char dest[], int n){
int temp, mod=1000, dest_i=0, i=0;
char formula;
if(n>MAXROMAN){
return 1;
}
while(mod){
temp=(n/mod);
for(formula=reglas[temp]; formula; formula>>=2){
dest[dest_i++]=seq[i][(formula&MASK)-1];
}
i++;
n = n%mod; /*n-=(n/mod)*mod;*/
mod=mod/10;
}
dest[dest_i]='\0';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment