đŸ› ïžToolsShed

Roman Numeral Arithmetic

Perform addition, subtraction, multiplication, and division with Roman numerals.

= 14

= 9

RomanNumeralArithmetic.reference

I

1

V

5

X

10

L

50

C

100

D

500

M

1000

RomanNumeralArithmetic.rules

  • RomanNumeralArithmetic.rule1
  • RomanNumeralArithmetic.rule2
  • RomanNumeralArithmetic.rule3

Questions Fréquentes

Implémentation du Code

ROMAN_VALUES = [
    (1000,'M'),(900,'CM'),(500,'D'),(400,'CD'),(100,'C'),(90,'XC'),
    (50,'L'),(40,'XL'),(10,'X'),(9,'IX'),(5,'V'),(4,'IV'),(1,'I')
]

def to_int(roman: str) -> int:
    """Convert Roman numeral string to integer."""
    values = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
    result, prev = 0, 0
    for ch in reversed(roman.upper()):
        val = values[ch]
        if val < prev:
            result -= val
        else:
            result += val
        prev = val
    return result

def to_roman(n: int) -> str:
    """Convert integer (1-3999) to Roman numeral string."""
    if not 1 <= n <= 3999:
        raise ValueError("Number must be between 1 and 3999")
    result = ""
    for value, numeral in ROMAN_VALUES:
        while n >= value:
            result += numeral
            n -= value
    return result

# Arithmetic operations
def roman_add(a: str, b: str) -> str:
    return to_roman(to_int(a) + to_int(b))

def roman_sub(a: str, b: str) -> str:
    return to_roman(to_int(a) - to_int(b))

def roman_mul(a: str, b: str) -> str:
    return to_roman(to_int(a) * to_int(b))

def roman_div(a: str, b: str) -> str:
    r = to_int(a) // to_int(b)
    return to_roman(r)

# Examples
print(f"XIV + IX = {roman_add('XIV', 'IX')}")    # 14+9=23 = XXIII
print(f"L - XIII = {roman_sub('L', 'XIII')}")    # 50-13=37 = XXXVII
print(f"V × IV = {roman_mul('V', 'IV')}")         # 5×4=20 = XX
print(f"XX Ă· IV = {roman_div('XX', 'IV')}")       # 20Ă·4=5 = V

# Convert between formats
for n in [1, 4, 9, 14, 40, 90, 399, 1994, 2024]:
    print(f"{n} = {to_roman(n)}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.