Problem: Write a Python program that takes an integer as a number and converts any number from 1 to 5000 into a Roman numeral equivalent.

Roman numerals are represented by seven different letters: I, V, X, L, C, D, and M which represent the numbers 1, 5, 10, 50, 100, 500, and 1,000 respectively. These seven letters are used to make thousands of numbers.

For example, the Roman numeral for two is written as ‘II’, just two one’s added together.

The numeral twelve is written as, XII, which is simply X + II.

knowtheromans.co.uk

To write 2 into roman numeral, we take two 1(I), which makes II.

Similarly, to write 12 into roman numeral, we take 10(X) and 2(II) i.e. XII.

If we observe closely then we get that roman numeral adds the required seven fundamental numerals in descending order to make up the numeber.

For example, 1012 = 1000(M) + 10(X) + 2(II) = MXII.

But exceptions are there like 4 is equivalent to ‘IV’ not ‘IIII’. Similarly, 9 is equivalent to ‘IX’.

In such cases, we subtract the left character value from the right character value i.e. 5(V) – 1(I) = 4(IV) or 10(X) – 1(I) = 9(IX) or 50(L) – 10(X) = 40(XL).

To include these exceptions into consideration, we include some more numbers into fundamental roman numerals i.e. 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, and 900, 1,000

Now, we can use these 13 fundamental roman equivalent integers to convert any integer to its roman equivalent.

So, to convert an integer into its corresponding roman numeral, we basically have to implement the following steps in Python:

  1. Divide the input number with the integer equivalent of 13 roman numerals in descending order.
  2. If the division is feasible i.e. quotient is not zero then it means the roman numerical equivalent of the divisor constitutes the resultant roman number.
  3. Output the Roman equivalent of the divisor as many times the quotient value.
  4. Update the input integer value to the remainder of the division.
  5. Repeat the above steps for all 13 fundamental roman numerals as the divisor (If the integer is not zero).

Here is the implementation of the steps in Python:

Enter a number: 999
CMXCIX


In this program, the intToroman dictionary stores 13 fundamental integers to roman numeral mapping as key: value pairs.

The print_order list contains intToroman keys sorted in descending order.

We use the print_order values as divisors and get their equivalent roman numeral from intToroman dictionary.

In this tutorial, we learned to convert an integer to its equivalent roman numeral in Python programming language.

Leave a Reply