How to Convert Arabic Numerals to Roman Numerals with Go

Roman numerals are an ancient numeral system used by the Romans that represents numbers by a combination of letters. Arabic numerals, which are the ones commonly used today (0-9), can be converted to Roman numerals by following some well-defined rules. This article will explain how to implement an Arabic to Roman numeral converter using the Go programming language.

First, a brief introduction to Roman numerals. The main symbols are:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

The main rules for conversion are:

  • A larger symbol preceding a smaller one is added (e.g. VI = 6, XV = 15).
  • A smaller symbol preceding a larger one is subtracted (e.g. IV = 4, IX = 9).

The logic of converting Arabic numerals to Roman numerals can be described in these steps:

  1. We create a map of all Roman values ​​with their Arabic equivalents.
  2. We iterate over the map starting from the largest Arabic number and continue subtracting from the Arabic number as many times as possible, adding the corresponding Roman symbol to the output string.

package main

import (
  "fmt"
)

func arabicToRoman(n int) string {
  // We create a slice with the Arabic values ​​and their Roman equivalents
  values ​​:= []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
  symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}

  // The variable to store the final result
  roman := ""

  // We iterate over the values ​​and build the Roman numeral string
  for i := 0; i < len(values); i++ {
    for n >= values[i] {
      roman += symbols[i]
      n -= values[i]
    }
  }

  return roman
}

Code explanation:

  • Value and Symbol Map: We have created two slices: values contains the corresponding Arabic numbers, while symbols contains the equivalent Roman symbols. This map is iterated to build the Roman numeral.

  • Roman Numeral Construction: Inside the for loop, we continue to subtract values ​​from the Arabic numeral and concatenate the Roman symbols until we are down to 0.

Considerations:

  1. Number Ranges: Classical Roman numerals are primarily used to represent numbers up to a few thousand. With our approach, we can handle numbers up to about 3999. If you wanted larger numbers, you should consider using a different notation (such as Roman numerals with slashes to indicate multiplications by 1000).

  2. Negative Values ​​and Zeros: Roman numerals do not have a representation for zero or negative numbers. Therefore, it is advisable to add a check to handle these cases.

Conclusion

Converting Arabic numbers to Roman numbers using Go is a great exercise to understand basic programming logic and data structures like slices and loops. In this article, we have seen how to create a simple Arabic to Roman number converter, and how we can expand and improve the code to handle more complex scenarios.

Back to top