views:

150

answers:

5

Possible Duplicate:
How do you find a roman numeral equivalent of an integer

I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?

string Roman(int Num){...}

For example, Roman(1981) must produce "MCMLXXXI".

+1  A: 

Here is a lengthy explanation how to do it with a lot of source code attached:

http://www.faqs.org/docs/javap/c9/ex-9-3-answer.html

But I think it could be done more efficient.

Roflcoptr
+1  A: 

Check out the code at this ActiveState link. The code looks fairly well documented.

Topher Fangio
+3  A: 

I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.

dsimcha
+1  A: 

I can't think of a third party library that has this functionality. Sometimes you have to write some stuff yourself, although there are plenty of examples of how do to this online. Here is one from RoseIndia

mR_fr0g
A: 

For hundreds, tens and units the rule is pretty much the same, i.e. you have a 1, 5 and 10 character the representation will be the same for each, just that the letters change.

You could have a table of 10 entries which represents a template 0 - 1 = U 2 = UU 3 = UUU 4 = UF 5 = F 6 = FU 7 = FUU 8 = FUUU 9 = UT

Now also have for units, tens and hundreds your table: Units = IVX Tens = XLC Hundreds = CDM

Apply your template for the number to the letter representation so a U is replaced by the first character, an F by the second and a T by the 3rd.

Thousands are just an M for each thousand.

Build your string starting with the thousands, then the hundreds, then the tens and then the units.

If you were building it backwards of course you could start with the units modding by 10, then construct your units string, divide by 10 and mod again and shift to the tens string, repeat with the hundreds string and when you get to the thousands string you will know it by the fact your string has just one character i.e. an M.

CashCow