Converting Between Arabic and Roman Numerals

Understanding Roman Numerals

Roman numerals do not use positional notation. In positional systems, a digit's value depends on both its symbol and its position. Roman numerals can appear in non-sequential order (such as IV for 4), making them non-positional. The system fell out of common use because it lacks a symbol for zero, becomes cumbersome for large numbers, and requires more complex rules for representation.

Python Implementation for Conversion

Here's a complete implementation for bidirectional conversion between Arabic and Roman numerals:

def arabic_to_roman(number: int) -> str:
    value_map = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    symbol_map = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    result = []
    
    for value, symbol in zip(value_map, symbol_map):
        count = number // value
        if count:
            result.append(symbol * count)
            number -= value * count
    
    return ''.join(result)

def roman_to_arabic(roman: str) -> int:
    symbol_values = {
        'I': 1, 'V': 5, 'X': 10, 'L': 50,
        'C': 100, 'D': 500, 'M': 1000
    }
    
    total = 0
    prev_value = 0
    
    for char in reversed(roman):
        value = symbol_values[char]
        if value < prev_value:
            total -= value
        else:
            total += value
            prev_value = value
    
    return total

def main():
    print("Arabic to Roman Converter")
    arabic_input = int(input("Enter Arabic number: "))
    roman_result = arabic_to_roman(arabic_input)
    print(f"{arabic_input} -> {roman_result}")
    
    print("\nRoman to Arabic Converter")
    roman_input = input("Enter Roman numeral: ").upper()
    arabic_result = roman_to_arabic(roman_input)
    print(f"{roman_input} -> {arabic_result}")

if __name__ == "__main__":
    main()

This implementation handles standard Roman numeral rules including subtractive notation (IV, IX, XL, XC, CD, CM). The conversion functions work efficiently for numbers up to 3999, which is the conventional upper limit for standard Roman numerals.

Tags: roman-numerals python Conversion algorithms

Posted on Mon, 24 Aug 2026 16:36:15 +0000 by marq