Programming Search⌘K

Taskintro

Convert to and from Roman numerals

Also called roman numerals, to roman, from roman, roman numeral encode, roman numeral decode, parse roman numerals, subtractive notation.

Convert an integer from 1 to 3999 to a Roman numeral with a table of values, and parse a Roman numeral back. A strict parser rejects forms such as IIII and IC.

Task

Convert a positive integer to a Roman numeral, and convert a Roman numeral back to an integer. The Rosetta Code task says: "Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero"1. For example, 1990 is M (1000), CM (900) and XC (90), so it is MCMXC.

The seven symbols are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000). Six pairs use subtractive notation: "The numerals for 4 (IV) and 9 (IX) are written using subtractive notation"2, and "Subtractive notation is also used for 40 (XL), 90 (XC), 400 (CD) and 900 (CM)"2.

The function to_roman(n) returns the Roman numeral of n as a string. For example, to_roman(1994) is "MCMXCIV". The function from_roman(s) returns the integer, or an error if s is not a valid numeral in the standard form.

The range is 1 to 3999. There is no symbol for 0: "the system as used by the Romans lacked a numeral for the number zero itself"2. And "The largest number that can be represented in this manner is 3,999 (MMMCMXCIX)"2, because the standard form uses no more than three M symbols.

The conversion to a numeral uses a table of the 13 values and their symbols, from the largest to the smallest: 1000 M, 900 CM, 500 D, 400 CD, 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV and 1 I. For each row, while n is at least the value, append the symbol and subtract the value. The table has the six subtractive pairs, so the greedy loop never writes IIII.

The conversion back reads the symbols from left to right. If a symbol is smaller than the next symbol, subtract its value. Otherwise, add its value. So in XC, the X is subtracted and the C is added: 100 minus 10 is 90.

Solutions

The standard libraries of the tier 1 languages have no Roman numeral functions, so each solution uses the table.

Language Table Errors
Python a tuple of pairs ValueError
JavaScript, TypeScript an array of pairs RangeError and SyntaxError
Java two arrays IllegalArgumentException
C# an array of tuples ArgumentOutOfRangeException and FormatException
Go a slice of structs error values
Rust an array of tuples Option
C an array of structs a return value of -1
C++ a constexpr array of pairs std::out_of_range and std::optional
Bash two arrays the exit status 1
  • Python. The table is a tuple of (value, symbol) pairs. from_roman raises ValueError for an invalid numeral.
  • JavaScript. The table is an array of pairs. toRoman throws RangeError for a number out of the range, and fromRoman throws SyntaxError for an invalid numeral.
  • TypeScript. The same code as JavaScript, with types.
  • Java. The table is two arrays, one of values and one of symbols. The functions throw IllegalArgumentException for bad input.
  • C#. The table is an array of tuples. ToRoman throws ArgumentOutOfRangeException, and FromRoman throws FormatException.
  • Go. The table is a slice of structs. Both functions return an error value as the second result.
  • Rust. The table is an array of tuples. Both functions return None for bad input.
  • C. to_roman writes the numeral into a buffer of 16 bytes, which holds the longest numeral, MMMDCCCLXXXVIII, and the null byte. Both functions return -1 for bad input.
  • C++. The table is a constexpr array. to_roman throws std::out_of_range, and from_roman returns an empty std::optional for an invalid numeral.
  • Bash. The table is two arrays. Both functions print the result, and return the exit status 1 for bad input.

The conversion to a numeral in Python:

TABLE = (
    (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_roman(n):
    if not 1 <= n <= 3999:
        raise ValueError("n is out of range")
    parts = []
    for value, symbol in TABLE:
        while n >= value:
            parts.append(symbol)
            n -= value
    return "".join(parts)


print(to_roman(1990), to_roman(2008), to_roman(1666), to_roman(3999))
Output
MCMXC MMVIII MDCLXVI MMMCMXCIX

The conversion back, with a check. The loop accepts some strings that are not in the standard form, so the function converts the result to a numeral again and compares it with the input:

VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
TABLE = (
    (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_roman(n):
    parts = []
    for value, symbol in TABLE:
        while n >= value:
            parts.append(symbol)
            n -= value
    return "".join(parts)


def from_roman(s):
    if not s or any(c not in VALUES for c in s):
        raise ValueError("not a Roman numeral")
    total = 0
    for i, c in enumerate(s):
        value = VALUES[c]
        if i + 1 < len(s) and value < VALUES[s[i + 1]]:
            total -= value
        else:
            total += value
    if total > 3999 or to_roman(total) != s:
        raise ValueError("not in the standard form")
    return total


print(from_roman("MCMXC"), from_roman("MMVIII"), from_roman("XCIX"))
for s in ["IC", "IIII", "MMMM", ""]:
    try:
        from_roman(s)
    except ValueError as e:
        print(repr(s), e)
Output
1990 2008 99
'IC' not in the standard form
'IIII' not in the standard form
'MMMM' not in the standard form
'' not a Roman numeral

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. They are for to_roman. The tests of each solution also convert each number from 1 to 3999 to a numeral and back, and check that from_roman rejects invalid strings.

  • year-1990, year-2008 and each-symbol-once: the examples of the Rosetta Code task. 1666 "uses each Roman symbol in descending order: MDCLXVI"1.
  • one: 1 is I, the smallest numeral.
  • four and nine: IV and IX, the subtractive pairs.
  • forty-nine and ninety-nine: XLIX and XCIX. Each digit is written on its own, so 49 is not IL, and 99 is not IC.
  • four-hundred-forty-four and year-1994: numbers with three subtractive pairs.
  • longest: 3888 is MMMDCCCLXXXVIII, with 15 symbols, the longest numeral in the range.
  • largest: 3999 is MMMCMXCIX.

Pitfalls

  • A table without the subtractive pairs. A greedy loop with only the seven symbols writes the additive forms, such as IIII for 4. These forms are in old texts, but "subtractive notation for 4, 40, and 400 (IV, XL, and CD) is the modern standard"2:

This code runs but gives a wrong answer on purpose.

TABLE = ((1000, "M"), (500, "D"), (100, "C"), (50, "L"), (10, "X"), (5, "V"), (1, "I"))


def to_roman(n):
    parts = []
    for value, symbol in TABLE:
        while n >= value:
            parts.append(symbol)
            n -= value
    return "".join(parts)


print(to_roman(1994))
Output
MDCCCCLXXXXIIII
  • The parser accepts invalid numerals. The Rosetta Code task for the conversion back says: "You don't need to validate the form of the Roman numeral"3. A parser with no check gives a value for strings that are not valid numerals:

This code runs but gives a wrong answer on purpose.

const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };

function fromRoman(s) {
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const value = values[s[i]];
    if (i + 1 < s.length && value < values[s[i + 1]]) {
      total -= value;
    } else {
      total += value;
    }
  }
  return total;
}

console.log(fromRoman("IIII"), fromRoman("IC"), fromRoman("VX"), fromRoman("I2"));
Output
4 99 5 NaN

To reject them, convert the result to a numeral again, and compare it with the input. Also reject the empty string and each character that is not a symbol.

  • Zero and negative numbers. There is no Roman numeral for 0. The greedy loop returns an empty string for 0 and for each negative number, with no error. Check the range first:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

var values = []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
var symbols = []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}

func toRoman(n int) string {
	s := ""
	for i, v := range values {
		for n >= v {
			s += symbols[i]
			n -= v
		}
	}
	return s
}

func main() {
	fmt.Printf("%q %q %q\n", toRoman(7), toRoman(0), toRoman(-5))
}
Output
"VII" "" ""
  • Lowercase letters. Some texts write Roman numerals in lowercase, such as xiv. The solutions on this page accept only uppercase letters. To accept lowercase letters, convert the input to uppercase first.

Code

The build runs the native tests of each language in a pinned toolchain.

roman.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

TABLE = (
    (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"),
)
VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}


def to_roman(n: int) -> str:
    """Return the Roman numeral of n, for 1 <= n <= 3999."""
    if not 1 <= n <= 3999:
        raise ValueError("n is out of range")
    parts = []
    for value, symbol in TABLE:
        while n >= value:
            parts.append(symbol)
            n -= value
    return "".join(parts)


def from_roman(s: str) -> int:
    """Return the value of a Roman numeral in the standard form."""
    if not s or any(c not in VALUES for c in s):
        raise ValueError("not a Roman numeral")
    total = 0
    for i, c in enumerate(s):
        value = VALUES[c]
        if i + 1 < len(s) and value < VALUES[s[i + 1]]:
            total -= value
        else:
            total += value
    if not 1 <= total <= 3999 or to_roman(total) != s:
        raise ValueError("not in the standard form")
    return total
test_roman.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

import pytest

from roman import from_roman, to_roman

CASES = [
    ("year-1990", 1990, "MCMXC"),
    ("year-2008", 2008, "MMVIII"),
    ("each-symbol-once", 1666, "MDCLXVI"),
    ("one", 1, "I"),
    ("four", 4, "IV"),
    ("nine", 9, "IX"),
    ("forty-nine", 49, "XLIX"),
    ("ninety-nine", 99, "XCIX"),
    ("four-hundred-forty-four", 444, "CDXLIV"),
    ("year-1994", 1994, "MCMXCIV"),
    ("longest", 3888, "MMMDCCCLXXXVIII"),
    ("largest", 3999, "MMMCMXCIX"),
]


@pytest.mark.parametrize(("name", "n", "want"), CASES, ids=[c[0] for c in CASES])
def test_to_roman(name, n, want):
    assert to_roman(n) == want
    assert from_roman(want) == n


def test_round_trip():
    for n in range(1, 4000):
        assert from_roman(to_roman(n)) == n


@pytest.mark.parametrize("s", ["", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"])
def test_invalid(s):
    with pytest.raises(ValueError):
        from_roman(s)


@pytest.mark.parametrize("n", [0, -1, 4000])
def test_out_of_range(n):
    with pytest.raises(ValueError):
        to_roman(n)
roman.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

#ifndef ROMAN_HPP
#define ROMAN_HPP

#include <array>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

inline constexpr std::array<std::pair<int, std::string_view>, 13> roman_table{{
    {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"},
}};

// Returns the Roman numeral of n. Throws std::out_of_range if n is not in
// 1 to 3999.
inline std::string to_roman(int n) {
    if (n < 1 || n > 3999) {
        throw std::out_of_range("n is out of range");
    }
    std::string s;
    for (const auto& [value, symbol] : roman_table) {
        while (n >= value) {
            s += symbol;
            n -= value;
        }
    }
    return s;
}

constexpr int roman_value(char c) {
    switch (c) {
    case 'I': return 1;
    case 'V': return 5;
    case 'X': return 10;
    case 'L': return 50;
    case 'C': return 100;
    case 'D': return 500;
    case 'M': return 1000;
    default: return 0;
    }
}

// Returns the value of a Roman numeral in the standard form, or no value.
inline std::optional<int> from_roman(std::string_view s) {
    if (s.empty()) {
        return std::nullopt;
    }
    int total = 0;
    for (std::size_t i = 0; i < s.size(); ++i) {
        const int v = roman_value(s[i]);
        if (v == 0) {
            return std::nullopt;
        }
        const int next = i + 1 < s.size() ? roman_value(s[i + 1]) : 0;
        total += v < next ? -v : v;
    }
    if (total < 1 || total > 3999 || to_roman(total) != s) {
        return std::nullopt;
    }
    return total;
}

#endif
test_roman.cpp 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

#include <cstdio>
#include <stdexcept>
#include <string_view>

#include "roman.hpp"

namespace {

struct test_case {
    const char* name;
    int n;
    const char* want;
};

const test_case cases[] = {
    {"year-1990", 1990, "MCMXC"},
    {"year-2008", 2008, "MMVIII"},
    {"each-symbol-once", 1666, "MDCLXVI"},
    {"one", 1, "I"},
    {"four", 4, "IV"},
    {"nine", 9, "IX"},
    {"forty-nine", 49, "XLIX"},
    {"ninety-nine", 99, "XCIX"},
    {"four-hundred-forty-four", 444, "CDXLIV"},
    {"year-1994", 1994, "MCMXCIV"},
    {"longest", 3888, "MMMDCCCLXXXVIII"},
    {"largest", 3999, "MMMCMXCIX"},
};

const std::string_view invalid[] = {"", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        if (to_roman(c.n) != c.want || from_roman(c.want) != c.n) {
            std::printf("FAIL %s\n", c.name);
            ++failures;
        }
    }
    for (int n = 1; n <= 3999; ++n) {
        if (from_roman(to_roman(n)) != n) {
            std::printf("FAIL round trip %d\n", n);
            ++failures;
        }
    }
    for (const auto s : invalid) {
        if (from_roman(s).has_value()) {
            std::printf("FAIL invalid\n");
            ++failures;
        }
    }
    for (const int n : {0, -1, 4000}) {
        try {
            (void)to_roman(n);
            std::printf("FAIL out of range %d\n", n);
            ++failures;
        } catch (const std::out_of_range&) {
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Roman.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

/** Conversion between integers and Roman numerals in the standard form. */
public final class Roman {
    private static final int[] VALUES = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    private static final String[] SYMBOLS = {
        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
    };

    private Roman() {}

    /** Returns the Roman numeral of n, for 1 <= n <= 3999. */
    public static String toRoman(long n) {
        if (n < 1 || n > 3999) {
            throw new IllegalArgumentException("n is out of range: " + n);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < VALUES.length; i++) {
            while (n >= VALUES[i]) {
                sb.append(SYMBOLS[i]);
                n -= VALUES[i];
            }
        }
        return sb.toString();
    }

    /** Returns the value of a Roman numeral in the standard form. */
    public static int fromRoman(String s) {
        if (s.isEmpty()) {
            throw new IllegalArgumentException("not a Roman numeral");
        }
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            int value = value(s.charAt(i));
            if (value == 0) {
                throw new IllegalArgumentException("not a Roman numeral: " + s);
            }
            int next = i + 1 < s.length() ? value(s.charAt(i + 1)) : 0;
            total += value < next ? -value : value;
        }
        if (total < 1 || total > 3999 || !toRoman(total).equals(s)) {
            throw new IllegalArgumentException("not in the standard form: " + s);
        }
        return total;
    }

    private static int value(char c) {
        return switch (c) {
            case 'I' -> 1;
            case 'V' -> 5;
            case 'X' -> 10;
            case 'L' -> 50;
            case 'C' -> 100;
            case 'D' -> 500;
            case 'M' -> 1000;
            default -> 0;
        };
    }
}
RomanTest.java 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

class RomanTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("year-1990", 1990, "MCMXC"),
                Arguments.of("year-2008", 2008, "MMVIII"),
                Arguments.of("each-symbol-once", 1666, "MDCLXVI"),
                Arguments.of("one", 1, "I"),
                Arguments.of("four", 4, "IV"),
                Arguments.of("nine", 9, "IX"),
                Arguments.of("forty-nine", 49, "XLIX"),
                Arguments.of("ninety-nine", 99, "XCIX"),
                Arguments.of("four-hundred-forty-four", 444, "CDXLIV"),
                Arguments.of("year-1994", 1994, "MCMXCIV"),
                Arguments.of("longest", 3888, "MMMDCCCLXXXVIII"),
                Arguments.of("largest", 3999, "MMMCMXCIX")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void toRoman(String name, long n, String want) {
        assertEquals(want, Roman.toRoman(n));
        assertEquals(n, Roman.fromRoman(want));
    }

    @Test
    void roundTrip() {
        for (int n = 1; n <= 3999; n++) {
            assertEquals(n, Roman.fromRoman(Roman.toRoman(n)));
        }
    }

    @ParameterizedTest
    @ValueSource(strings = {"", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"})
    void invalid(String s) {
        assertThrows(IllegalArgumentException.class, () -> Roman.fromRoman(s));
    }

    @ParameterizedTest
    @ValueSource(longs = {0, -1, 4000})
    void outOfRange(long n) {
        assertThrows(IllegalArgumentException.class, () -> Roman.toRoman(n));
    }
}
roman.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

#include "roman.h"

#include <string.h>

static const struct {
    int value;
    const char *symbol;
} table[] = {
    {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"},
};

int to_roman(int n, char *out, size_t size) {
    if (n < 1 || n > 3999 || size < ROMAN_SIZE) {
        return -1;
    }
    size_t len = 0;
    for (size_t i = 0; i < sizeof table / sizeof table[0]; i++) {
        while (n >= table[i].value) {
            size_t k = strlen(table[i].symbol);
            memcpy(out + len, table[i].symbol, k);
            len += k;
            n -= table[i].value;
        }
    }
    out[len] = '\0';
    return 0;
}

static int value(char c) {
    switch (c) {
    case 'I': return 1;
    case 'V': return 5;
    case 'X': return 10;
    case 'L': return 50;
    case 'C': return 100;
    case 'D': return 500;
    case 'M': return 1000;
    default: return 0;
    }
}

int from_roman(const char *s) {
    size_t len = strlen(s);
    if (len == 0 || len >= ROMAN_SIZE) {
        return -1;
    }
    int total = 0;
    for (size_t i = 0; i < len; i++) {
        int v = value(s[i]);
        if (v == 0) {
            return -1;
        }
        int next = i + 1 < len ? value(s[i + 1]) : 0;
        total += v < next ? -v : v;
    }
    char back[ROMAN_SIZE];
    if (to_roman(total, back, sizeof back) != 0 || strcmp(back, s) != 0) {
        return -1;
    }
    return total;
}
roman.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

#ifndef ROMAN_H
#define ROMAN_H

#include <stddef.h>

// The size of a buffer for the longest numeral, MMMDCCCLXXXVIII, and the
// null byte.
#define ROMAN_SIZE 16

// Writes the Roman numeral of n into out. Returns 0, or -1 if n is not in
// 1 to 3999 or size is less than ROMAN_SIZE.
int to_roman(int n, char *out, size_t size);

// Returns the value of a Roman numeral in the standard form, or -1.
int from_roman(const char *s);

#endif
test_roman.c 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

#include "roman.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    int n;
    const char *want;
};

static const struct test_case cases[] = {
    {"year-1990", 1990, "MCMXC"},
    {"year-2008", 2008, "MMVIII"},
    {"each-symbol-once", 1666, "MDCLXVI"},
    {"one", 1, "I"},
    {"four", 4, "IV"},
    {"nine", 9, "IX"},
    {"forty-nine", 49, "XLIX"},
    {"ninety-nine", 99, "XCIX"},
    {"four-hundred-forty-four", 444, "CDXLIV"},
    {"year-1994", 1994, "MCMXCIV"},
    {"longest", 3888, "MMMDCCCLXXXVIII"},
    {"largest", 3999, "MMMCMXCIX"},
};

static const char *const invalid[] = {"", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"};

int main(void) {
    int failures = 0;
    char buf[ROMAN_SIZE];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        if (to_roman(c->n, buf, sizeof buf) != 0 || strcmp(buf, c->want) != 0) {
            printf("FAIL %s: to_roman\n", c->name);
            failures++;
        }
        if (from_roman(c->want) != c->n) {
            printf("FAIL %s: from_roman\n", c->name);
            failures++;
        }
    }
    for (int n = 1; n <= 3999; n++) {
        if (to_roman(n, buf, sizeof buf) != 0 || from_roman(buf) != n) {
            printf("FAIL round trip %d\n", n);
            failures++;
        }
    }
    for (size_t i = 0; i < sizeof invalid / sizeof invalid[0]; i++) {
        if (from_roman(invalid[i]) != -1) {
            printf("FAIL invalid \"%s\"\n", invalid[i]);
            failures++;
        }
    }
    if (to_roman(0, buf, sizeof buf) != -1 || to_roman(4000, buf, sizeof buf) != -1) {
        printf("FAIL out of range\n");
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Roman.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

using System;
using System.Text;

/// <summary>Conversion between integers and Roman numerals in the standard form.</summary>
public static class Roman
{
    private static readonly (int Value, string Symbol)[] Table = new (int, string)[]
    {
        (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"),
    };

    /// <summary>Returns the Roman numeral of n, for 1 &lt;= n &lt;= 3999.</summary>
    public static string ToRoman(long n)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(n, 1);
        ArgumentOutOfRangeException.ThrowIfGreaterThan(n, 3999);
        var sb = new StringBuilder();
        foreach (var (value, symbol) in Table)
        {
            while (n >= value)
            {
                sb.Append(symbol);
                n -= value;
            }
        }
        return sb.ToString();
    }

    /// <summary>Returns the value of a Roman numeral in the standard form.</summary>
    public static int FromRoman(string s)
    {
        if (s.Length == 0)
        {
            throw new FormatException("not a Roman numeral");
        }
        int total = 0;
        for (int i = 0; i < s.Length; i++)
        {
            int value = Value(s[i]);
            if (value == 0)
            {
                throw new FormatException("not a Roman numeral");
            }
            int next = i + 1 < s.Length ? Value(s[i + 1]) : 0;
            total += value < next ? -value : value;
        }
        if (total < 1 || total > 3999 || ToRoman(total) != s)
        {
            throw new FormatException("not in the standard form");
        }
        return total;
    }

    private static int Value(char c) => c switch
    {
        'I' => 1,
        'V' => 5,
        'X' => 10,
        'L' => 50,
        'C' => 100,
        'D' => 500,
        'M' => 1000,
        _ => 0,
    };
}
RomanTests.cs 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

using System;
using Xunit;

public sealed class RomanTests
{
    public static TheoryData<string, long, string> Cases => new()
    {
        { "year-1990", 1990, "MCMXC" },
        { "year-2008", 2008, "MMVIII" },
        { "each-symbol-once", 1666, "MDCLXVI" },
        { "one", 1, "I" },
        { "four", 4, "IV" },
        { "nine", 9, "IX" },
        { "forty-nine", 49, "XLIX" },
        { "ninety-nine", 99, "XCIX" },
        { "four-hundred-forty-four", 444, "CDXLIV" },
        { "year-1994", 1994, "MCMXCIV" },
        { "longest", 3888, "MMMDCCCLXXXVIII" },
        { "largest", 3999, "MMMCMXCIX" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ToRoman(string name, long n, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Roman.ToRoman(n));
        Assert.Equal(n, Roman.FromRoman(want));
    }

    [Fact]
    public void RoundTrip()
    {
        for (int n = 1; n <= 3999; n++)
        {
            Assert.Equal(n, Roman.FromRoman(Roman.ToRoman(n)));
        }
    }

    [Theory]
    [InlineData("")]
    [InlineData("IIII")]
    [InlineData("IC")]
    [InlineData("VX")]
    [InlineData("MMMM")]
    [InlineData("iv")]
    [InlineData("ABC")]
    [InlineData("IIV")]
    [InlineData("XM")]
    public void Invalid(string s)
    {
        Assert.Throws<FormatException>(() => Roman.FromRoman(s));
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-1)]
    [InlineData(4000)]
    public void OutOfRange(long n)
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => Roman.ToRoman(n));
    }
}
roman.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

const TABLE = [
  [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"],
];
const VALUES = new Map([
  ["I", 1], ["V", 5], ["X", 10], ["L", 50], ["C", 100], ["D", 500], ["M", 1000],
]);

/** Returns the Roman numeral of n, for 1 <= n <= 3999. */
export function toRoman(n) {
  if (!Number.isInteger(n) || n < 1 || n > 3999) {
    throw new RangeError("n is out of range");
  }
  let s = "";
  for (const [value, symbol] of TABLE) {
    while (n >= value) {
      s += symbol;
      n -= value;
    }
  }
  return s;
}

/** Returns the value of a Roman numeral in the standard form. */
export function fromRoman(s) {
  if (s.length === 0) {
    throw new SyntaxError("not a Roman numeral");
  }
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const value = VALUES.get(s[i]);
    if (value === undefined) {
      throw new SyntaxError("not a Roman numeral");
    }
    const next = i + 1 < s.length ? (VALUES.get(s[i + 1]) ?? 0) : 0;
    total += value < next ? -value : value;
  }
  if (total < 1 || total > 3999 || toRoman(total) !== s) {
    throw new SyntaxError("not in the standard form");
  }
  return total;
}
roman.test.js 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fromRoman, toRoman } from "./roman.js";

const cases = [
  ["year-1990", 1990, "MCMXC"],
  ["year-2008", 2008, "MMVIII"],
  ["each-symbol-once", 1666, "MDCLXVI"],
  ["one", 1, "I"],
  ["four", 4, "IV"],
  ["nine", 9, "IX"],
  ["forty-nine", 49, "XLIX"],
  ["ninety-nine", 99, "XCIX"],
  ["four-hundred-forty-four", 444, "CDXLIV"],
  ["year-1994", 1994, "MCMXCIV"],
  ["longest", 3888, "MMMDCCCLXXXVIII"],
  ["largest", 3999, "MMMCMXCIX"],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(toRoman(n), want);
    assert.equal(fromRoman(want), n);
  });
}

test("round trip", () => {
  for (let n = 1; n <= 3999; n++) {
    assert.equal(fromRoman(toRoman(n)), n);
  }
});

test("invalid", () => {
  for (const s of ["", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"]) {
    assert.throws(() => fromRoman(s), SyntaxError, s);
  }
});

test("out of range", () => {
  for (const n of [0, -1, 4000]) {
    assert.throws(() => toRoman(n), RangeError);
  }
});
roman.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

const TABLE: [number, string][] = [
  [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"],
];
const VALUES: Map<string, number> = new Map([
  ["I", 1], ["V", 5], ["X", 10], ["L", 50], ["C", 100], ["D", 500], ["M", 1000],
]);

/** Returns the Roman numeral of n, for 1 <= n <= 3999. */
export function toRoman(n: number): string {
  if (!Number.isInteger(n) || n < 1 || n > 3999) {
    throw new RangeError("n is out of range");
  }
  let s = "";
  for (const [value, symbol] of TABLE) {
    while (n >= value) {
      s += symbol;
      n -= value;
    }
  }
  return s;
}

/** Returns the value of a Roman numeral in the standard form. */
export function fromRoman(s: string): number {
  if (s.length === 0) {
    throw new SyntaxError("not a Roman numeral");
  }
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const value = VALUES.get(s[i]);
    if (value === undefined) {
      throw new SyntaxError("not a Roman numeral");
    }
    const next = i + 1 < s.length ? (VALUES.get(s[i + 1]) ?? 0) : 0;
    total += value < next ? -value : value;
  }
  if (total < 1 || total > 3999 || toRoman(total) !== s) {
    throw new SyntaxError("not in the standard form");
  }
  return total;
}
roman.test.ts 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fromRoman, toRoman } from "./roman.ts";

const cases: [string, number, string][] = [
  ["year-1990", 1990, "MCMXC"],
  ["year-2008", 2008, "MMVIII"],
  ["each-symbol-once", 1666, "MDCLXVI"],
  ["one", 1, "I"],
  ["four", 4, "IV"],
  ["nine", 9, "IX"],
  ["forty-nine", 49, "XLIX"],
  ["ninety-nine", 99, "XCIX"],
  ["four-hundred-forty-four", 444, "CDXLIV"],
  ["year-1994", 1994, "MCMXCIV"],
  ["longest", 3888, "MMMDCCCLXXXVIII"],
  ["largest", 3999, "MMMCMXCIX"],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(toRoman(n), want);
    assert.equal(fromRoman(want), n);
  });
}

test("round trip", () => {
  for (let n = 1; n <= 3999; n++) {
    assert.equal(fromRoman(toRoman(n)), n);
  }
});

test("invalid", () => {
  for (const s of ["", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"]) {
    assert.throws(() => fromRoman(s), SyntaxError, s);
  }
});

test("out of range", () => {
  for (const n of [0, -1, 4000]) {
    assert.throws(() => toRoman(n), RangeError);
  }
});
roman.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

// Package roman converts between integers and Roman numerals in the standard form.
package roman

import (
	"errors"
	"strings"
)

var table = []struct {
	value  int64
	symbol string
}{
	{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"},
}

// ErrRange is the error for a number outside 1 to 3999.
var ErrRange = errors.New("roman: n is out of range")

// ErrSyntax is the error for a string that is not a Roman numeral in the standard form.
var ErrSyntax = errors.New("roman: not a Roman numeral in the standard form")

// ToRoman returns the Roman numeral of n, for 1 <= n <= 3999.
func ToRoman(n int64) (string, error) {
	if n < 1 || n > 3999 {
		return "", ErrRange
	}
	var b strings.Builder
	for _, row := range table {
		for n >= row.value {
			b.WriteString(row.symbol)
			n -= row.value
		}
	}
	return b.String(), nil
}

// FromRoman returns the value of a Roman numeral in the standard form.
func FromRoman(s string) (int64, error) {
	if s == "" {
		return 0, ErrSyntax
	}
	var total int64
	for i := 0; i < len(s); i++ {
		v := value(s[i])
		if v == 0 {
			return 0, ErrSyntax
		}
		var next int64
		if i+1 < len(s) {
			next = value(s[i+1])
		}
		if v < next {
			total -= v
		} else {
			total += v
		}
	}
	back, err := ToRoman(total)
	if err != nil || back != s {
		return 0, ErrSyntax
	}
	return total, nil
}

func value(c byte) int64 {
	switch c {
	case 'I':
		return 1
	case 'V':
		return 5
	case 'X':
		return 10
	case 'L':
		return 50
	case 'C':
		return 100
	case 'D':
		return 500
	case 'M':
		return 1000
	}
	return 0
}
roman_test.go 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

package roman

import (
	"errors"
	"testing"
)

var cases = []struct {
	name string
	n    int64
	want string
}{
	{"year-1990", 1990, "MCMXC"},
	{"year-2008", 2008, "MMVIII"},
	{"each-symbol-once", 1666, "MDCLXVI"},
	{"one", 1, "I"},
	{"four", 4, "IV"},
	{"nine", 9, "IX"},
	{"forty-nine", 49, "XLIX"},
	{"ninety-nine", 99, "XCIX"},
	{"four-hundred-forty-four", 444, "CDXLIV"},
	{"year-1994", 1994, "MCMXCIV"},
	{"longest", 3888, "MMMDCCCLXXXVIII"},
	{"largest", 3999, "MMMCMXCIX"},
}

func TestToRoman(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ToRoman(c.n)
			if err != nil || got != c.want {
				t.Fatalf("ToRoman(%d) = %q, %v, want %q", c.n, got, err, c.want)
			}
			back, err := FromRoman(c.want)
			if err != nil || back != c.n {
				t.Fatalf("FromRoman(%q) = %d, %v", c.want, back, err)
			}
		})
	}
}

func TestRoundTrip(t *testing.T) {
	for n := int64(1); n <= 3999; n++ {
		s, err := ToRoman(n)
		if err != nil {
			t.Fatal(err)
		}
		if back, err := FromRoman(s); err != nil || back != n {
			t.Fatalf("FromRoman(%q) = %d, %v", s, back, err)
		}
	}
}

func TestInvalid(t *testing.T) {
	for _, s := range []string{"", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"} {
		if _, err := FromRoman(s); !errors.Is(err, ErrSyntax) {
			t.Fatalf("FromRoman(%q): err = %v", s, err)
		}
	}
	for _, n := range []int64{0, -1, 4000} {
		if _, err := ToRoman(n); !errors.Is(err, ErrRange) {
			t.Fatalf("ToRoman(%d): err = %v", n, err)
		}
	}
}
roman.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

const TABLE: [(i64, &str); 13] = [
    (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"),
];

/// Returns the Roman numeral of n, or None if n is not in 1 to 3999.
pub fn to_roman(n: i64) -> Option<String> {
    if !(1..=3999).contains(&n) {
        return None;
    }
    let mut n = n;
    let mut s = String::new();
    for (value, symbol) in TABLE {
        while n >= value {
            s.push_str(symbol);
            n -= value;
        }
    }
    Some(s)
}

/// Returns the value of a Roman numeral in the standard form, or None.
pub fn from_roman(s: &str) -> Option<i64> {
    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let mut total = 0i64;
    for (i, &c) in bytes.iter().enumerate() {
        let v = value(c)?;
        let next = bytes.get(i + 1).and_then(|&d| value(d)).unwrap_or(0);
        if v < next {
            total -= v;
        } else {
            total += v;
        }
    }
    if to_roman(total)? == s {
        Some(total)
    } else {
        None
    }
}

fn value(c: u8) -> Option<i64> {
    match c {
        b'I' => Some(1),
        b'V' => Some(5),
        b'X' => Some(10),
        b'L' => Some(50),
        b'C' => Some(100),
        b'D' => Some(500),
        b'M' => Some(1000),
        _ => None,
    }
}
tests/roman_test.rs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

use algo_convert_to_and_from_roman_numerals::{from_roman, to_roman};

const CASES: &[(&str, i64, &str)] = &[
    ("year-1990", 1990, "MCMXC"),
    ("year-2008", 2008, "MMVIII"),
    ("each-symbol-once", 1666, "MDCLXVI"),
    ("one", 1, "I"),
    ("four", 4, "IV"),
    ("nine", 9, "IX"),
    ("forty-nine", 49, "XLIX"),
    ("ninety-nine", 99, "XCIX"),
    ("four-hundred-forty-four", 444, "CDXLIV"),
    ("year-1994", 1994, "MCMXCIV"),
    ("longest", 3888, "MMMDCCCLXXXVIII"),
    ("largest", 3999, "MMMCMXCIX"),
];

#[test]
fn cases() {
    for &(name, n, want) in CASES {
        assert_eq!(to_roman(n).as_deref(), Some(want), "{name}");
        assert_eq!(from_roman(want), Some(n), "{name}");
    }
}

#[test]
fn round_trip() {
    for n in 1..=3999 {
        let s = to_roman(n).expect("in range");
        assert_eq!(from_roman(&s), Some(n));
    }
}

#[test]
fn invalid() {
    for s in ["", "IIII", "IC", "VX", "MMMM", "iv", "ABC", "IIV", "XM"] {
        assert_eq!(from_roman(s), None, "{s}");
    }
    for n in [0, -1, 4000] {
        assert_eq!(to_roman(n), None);
    }
}
roman.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

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

# to_roman N
# Prints the Roman numeral of N. Returns 1 if N is not in 1 to 3999.
to_roman() {
  local n=$1 s="" i
  if ! [[ $n =~ ^[0-9]+$ ]] || ((n < 1 || n > 3999)); then
    return 1
  fi
  for i in "${!ROMAN_VALUES[@]}"; do
    while ((n >= ROMAN_VALUES[i])); do
      s+=${ROMAN_SYMBOLS[i]}
      n=$((n - ROMAN_VALUES[i]))
    done
  done
  printf '%s\n' "$s"
}

# from_roman S
# Prints the value of the Roman numeral S. Returns 1 if S is not a Roman
# numeral in the standard form.
from_roman() {
  local s=$1 total=0 i v next back
  if [[ -z $s || $s == *[!IVXLCDM]* ]]; then
    return 1
  fi
  for ((i = 0; i < ${#s}; i++)); do
    v=${ROMAN_DIGITS[${s:i:1}]}
    next=0
    if ((i + 1 < ${#s})); then
      next=${ROMAN_DIGITS[${s:i+1:1}]}
    fi
    if ((v < next)); then
      total=$((total - v))
    else
      total=$((total + v))
    fi
  done
  back=$(to_roman "$total") || return 1
  [[ $back == "$s" ]] || return 1
  printf '%s\n' "$total"
}
test_roman.bats 46 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-to-and-from-roman-numerals/.

setup() {
  source "$BATS_TEST_DIRNAME/roman.sh"
}

@test "year-1990" { run to_roman 1990; [ "$output" = 'MCMXC' ]; run from_roman 'MCMXC'; [ "$output" = "1990" ]; }
@test "year-2008" { run to_roman 2008; [ "$output" = 'MMVIII' ]; run from_roman 'MMVIII'; [ "$output" = "2008" ]; }
@test "each-symbol-once" { run to_roman 1666; [ "$output" = 'MDCLXVI' ]; run from_roman 'MDCLXVI'; [ "$output" = "1666" ]; }
@test "one" { run to_roman 1; [ "$output" = 'I' ]; run from_roman 'I'; [ "$output" = "1" ]; }
@test "four" { run to_roman 4; [ "$output" = 'IV' ]; run from_roman 'IV'; [ "$output" = "4" ]; }
@test "nine" { run to_roman 9; [ "$output" = 'IX' ]; run from_roman 'IX'; [ "$output" = "9" ]; }
@test "forty-nine" { run to_roman 49; [ "$output" = 'XLIX' ]; run from_roman 'XLIX'; [ "$output" = "49" ]; }
@test "ninety-nine" { run to_roman 99; [ "$output" = 'XCIX' ]; run from_roman 'XCIX'; [ "$output" = "99" ]; }
@test "four-hundred-forty-four" { run to_roman 444; [ "$output" = 'CDXLIV' ]; run from_roman 'CDXLIV'; [ "$output" = "444" ]; }
@test "year-1994" { run to_roman 1994; [ "$output" = 'MCMXCIV' ]; run from_roman 'MCMXCIV'; [ "$output" = "1994" ]; }
@test "longest" { run to_roman 3888; [ "$output" = 'MMMDCCCLXXXVIII' ]; run from_roman 'MMMDCCCLXXXVIII'; [ "$output" = "3888" ]; }
@test "largest" { run to_roman 3999; [ "$output" = 'MMMCMXCIX' ]; run from_roman 'MMMCMXCIX'; [ "$output" = "3999" ]; }

@test "round-trip" {
  # A sample of the numbers 1 to 3999, because bats is slow with thousands of subshells.
  local n s
  for ((n = 1; n <= 3999; n += 37)); do
    s=$(to_roman "$n")
    [ "$(from_roman "$s")" = "$n" ]
  done
}

@test "invalid" {
  local s
  for s in "" IIII IC VX MMMM iv ABC IIV XM; do
    run from_roman "$s"
    [ "$status" -eq 1 ]
  done
}

@test "out-of-range" {
  run to_roman 0
  [ "$status" -eq 1 ]
  run to_roman -1
  [ "$status" -eq 1 ]
  run to_roman 4000
  [ "$status" -eq 1 ]
}

References

  1. Rosetta Code, Roman numerals/Encode (task text, from acmeism/RosettaCodeData), task text
  2. Wikipedia, Roman numerals, Description; Other additive forms; Zero
  3. Rosetta Code, Roman numerals/Decode (task text, from acmeism/RosettaCodeData), task text

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source