Skip to content

Instantly share code, notes, and snippets.

@mjf
Last active December 24, 2015 06:29
Show Gist options
  • Save mjf/6757822 to your computer and use it in GitHub Desktop.
Save mjf/6757822 to your computer and use it in GitHub Desktop.
ar2rom - Convert Arabic numerals to Roman numerals
/**
* ar2rom - Convert Arabic numerals to Roman numerals
* Copyright (C) 2013 Matous J. Fialka, <http://mjf.cz/>
* Released under the terms of The MIT License
*
* Compile: cc -pedantic -ansi -Wall -Werror -o ar2rom ar2rom.c
*/
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int arg;
long left;
if(argc < 2) {
printf("usage: ar2rom [ARNUM ...]\n");
return 0;
}
for(arg = 1; arg < argc; arg++) {
left = atol(argv[arg]);
printf("%-16ld\t", left);
if(left < 1) {
printf("NaN\n");
continue;
}
while(left >= 1000)
left -= 1000, printf("M");
if(left >= 900) {
left -= 900;
printf("CM");
}
if(left >= 500) {
left -= 500;
printf("D");
}
if(left >= 400) {
left -= 400;
printf("CD");
}
while(left >= 100) {
left -= 100;
printf("C");
}
if(left >= 50) {
left -= 50;
printf("L");
}
if(left >= 40) {
left -= 40;
printf("XL");
}
while(left >= 10) {
left -= 10;
printf("X");
}
if(left >= 9) {
left -= 9;
printf("IX");
}
if(left >= 5) {
left -= 5;
printf("V");
}
if(left >= 4) {
left -= 4;
printf("IV");
}
while(left >= 1) {
left -= 1;
printf("I");
}
printf("\n");
}
return 0;
}
@mjf
Copy link
Author

mjf commented Oct 1, 2013

Example:

$ ar2rom 1979 2013 9999 -123
1979                    MCMLXXIX
2013                    MMXIII
9999                    MMMMMMMMMCMLXLIX
-123                    NaN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment