Converting Decimal Number lying between 1 to 3999 to Roman Numerals

Given a number, find its corresponding Roman numeral.
Examples:

Input : 9
Output : IX

Input : 40
Output : XL

Input :  1904
Output : MCMIV

Following is the list of Roman symbols which include subtractive cases also:

SYMBOL       VALUE
I             1
IV            4
V             5
IX            9
X             10
XL            40
L             50
XC            90
C             100
CD            400
D             500
CM            900 
M             1000       



Idea is to convert the units, tens, hundreds, and thousands places of the given number separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The conversion of digit’s 4’s and 9’s are little bit different from other digits because these digits follows subtractive notation.

Algorithm to convert decimal number to Roman Numeral
Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. Base value which is just smaller or equal to the given number will be the initial base value (largest base value) .Divide the number by its largest base value, the corresponding base symbol will be repeated quotient times, the remainder will then become the number for future division and repetitions.The process will be repeated until the number becomes zero.

Example to demonstrate above algorithm:

Convert 3549 to its Roman Numerals

Output:

MMMDXLIX

Explanation:

    Step 1

  • Initially number = 3549
  • Since 3549 >= 1000 ; largest base value will be 1000 initially.
  • Divide 3549/1000. Quotient = 3, Remainder =549. The corresponding symbol M will be repeated thrice.
  • Step 2

  • Now, number = 549
  • 1000 > 549 >= 500 ; largest base value will be 500.
  • Divide 549/500. Quotient = 1, Remainder =49. The corresponding symbol D will be repeated once.
  • Step 3

  • Now, number = 49
  • 50 > 49 >= 40 ; largest base value is 40.
  • Divide 49/40. Quotient = 1, Remainder = 9. The corresponding symbol XL will be repeated once.
  • Step 4

  • Now, number = 9
  • 10> 9 >= 9 ; largest base value is 9.
  • Divide 9/9. Quotient = 1, Remainder = 0. The corresponding symbol IX will be repeated once.
  • Step 5


  • Finally number becomes 0, algorithm stops here.
  • Output obtained MMMDXLIX.

Following is the implementation of the above algorithm:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to convert decimal number to
// roman numerals
#include <bits/stdc++.h>
using namespace std;
  
// Function to convert decimal to Roman Numerals
int printRoman(int number)
{
    int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
    string sym[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    int i=12;    
    while(number>0)
    {
      int div = number/num[i];
      number = number%num[i];
      while(div--)
      {
        cout<<sym[i];
      }
      i--;
    }
}
  
//Driver program
int main()
{
    int number = 3549;
  
    printRoman(number);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to convert decimal number to
// roman numerals
class GFG {
  
// To add corresponding base symbols in the array
// to handle cases that follow subtractive notation.
// Base symbols are added index 'i'.
    static int sub_digit(char num1, char num2, int i, char[] c) {
        c[i++] = num1;
        c[i++] = num2;
        return i;
    }
  
// To add symbol 'ch' n times after index i in c[]
    static int digit(char ch, int n, int i, char[] c) {
        for (int j = 0; j < n; j++) {
            c[i++] = ch;
        }
        return i;
    }
  
// Function to convert decimal to Roman Numerals
    static void printRoman(int number) {
        char c[] = new char[10001];
        int i = 0;
  
        // If number entered is not valid
        if (number <= 0) {
            System.out.printf("Invalid number");
            return;
        }
  
        // TO convert decimal number to roman numerals
        while (number != 0) {
            // If base value of number is greater than 1000
            if (number >= 1000) {
                // Add 'M' number/1000 times after index i
                i = digit('M', number / 1000, i, c);
                number = number % 1000;
            } // If base value of number is greater than or
            // equal to 500
            else if (number >= 500) {
                // To add base symbol to the character array
                if (number < 900) {
                    // Add 'D' number/1000 times after index i
                    i = digit('D', number / 500, i, c);
                    number = number % 500;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    // Add C and M after index i/.
                    i = sub_digit('C', 'M', i, c);
                    number = number % 100;
                }
            } // If base value of number is greater than or equal to 100
            else if (number >= 100) {
                // To add base symbol to the character array
                if (number < 400) {
                    i = digit('C', number / 100, i, c);
                    number = number % 100;
                } // To handle subtractive notation in case of number
                // having digit as 4 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('C', 'D', i, c);
                    number = number % 100;
                }
            } // If base value of number is greater than or equal to 50
            else if (number >= 50) {
                // To add base symbol to the character array
                if (number < 90) {
                    i = digit('L', number / 50, i, c);
                    number = number % 50;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('X', 'C', i, c);
                    number = number % 10;
                }
            } // If base value of number is greater than or equal to 10
            else if (number >= 10) {
                // To add base symbol to the character array
                if (number < 40) {
                    i = digit('X', number / 10, i, c);
                    number = number % 10;
                } // To handle subtractive notation in case of
                // number having digit as 4 and adding
                // corresponding base symbol
                else {
                    i = sub_digit('X', 'L', i, c);
                    number = number % 10;
                }
            } // If base value of number is greater than or equal to 5
            else if (number >= 5) {
                if (number < 9) {
                    i = digit('V', number / 5, i, c);
                    number = number % 5;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('I', 'X', i, c);
                    number = 0;
                }
            } // If base value of number is greater than or equal to 1
            else if (number >= 1) {
                if (number < 4) {
                    i = digit('I', number, i, c);
                    number = 0;
                } // To handle subtractive notation in case of
                // number having digit as 4 and adding corresponding
                // base symbol
                else {
                    i = sub_digit('I', 'V', i, c);
                    number = 0;
                }
            }
        }
  
        // Printing equivalent Roman Numeral
        System.out.printf("Roman numeral is: ");
        for (int j = 0; j < i; j++) {
            System.out.printf("%c", c[j]);
        }
    }
  
//Driver program
    public static void main(String[] args) {
        int number = 3549;
  
        printRoman(number);
    }
}
// This code is contributed by PrinciRaj1992 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to convert 
# decimal number to roman numerals
  
# Function to convert decimal to Roman Numerals
def printRoman(number):
    num = [1, 4, 5, 9, 10, 40, 50, 90
           100, 400, 500, 900, 1000]
    sym = ["I", "IV", "V", "IX", "X", "XL"
           "L", "XC", "C", "CD", "D", "CM", "M"]
    i = 12
    while number:
        div = number // num[i]
        number %= num[i]
  
        while div:
            print(sym[i], end = "")
            div -= 1
        i -= 1
  
# Driver code
if __name__ == "__main__":
    number = 3549
    print("Roman numeral is:", end = " ")
    printRoman(number)
      
# This code is contributed by
# sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to convert decimal number 
// to roman numerals 
using System;
class GFG 
  
// To add corresponding base symbols in the 
// array to handle cases which follow subtractive 
// notation. Base symbols are added index 'i'. 
static int sub_digit(char num1, char num2, 
                         int i, char[] c) 
    c[i++] = num1; 
    c[i++] = num2; 
    return i; 
  
// To add symbol 'ch' n times after index i in c[] 
static int digit(char ch, int n, int i, char[] c) 
    for (int j = 0; j < n; j++)
    
        c[i++] = ch; 
    
    return i; 
  
// Function to convert decimal to Roman Numerals 
static void printRoman(int number)
    char[] c = new char[10001]; 
    int i = 0; 
  
    // If number entered is not valid 
    if (number <= 0) 
    
        Console.WriteLine("Invalid number"); 
        return
    
  
    // TO convert decimal number to 
    // roman numerals 
    while (number != 0) 
    
        // If base value of number is 
        // greater than 1000 
        if (number >= 1000)
        
            // Add 'M' number/1000 times after index i 
            i = digit('M', number / 1000, i, c); 
            number = number % 1000; 
        }
          
        // If base value of number is greater 
        // than or equal to 500 
        else if (number >= 500) 
        
            // To add base symbol to the character array 
            if (number < 900) 
            
                  
                // Add 'D' number/1000 times after index i 
                i = digit('D', number / 500, i, c); 
                number = number % 500; 
            
              
            // To handle subtractive notation in case 
            // of number having digit as 9 and adding 
            // corresponding base symbol 
            else 
            
                  
                // Add C and M after index i/. 
                i = sub_digit('C', 'M', i, c); 
                number = number % 100; 
            
        }
          
        // If base value of number is greater 
        // than or equal to 100 
        else if (number >= 100) 
        
            // To add base symbol to the character array 
            if (number < 400) 
            
                i = digit('C', number / 100, i, c); 
                number = number % 100; 
            
              
            // To handle subtractive notation in case 
            // of number having digit as 4 and adding 
            // corresponding base symbol 
            else 
            
                i = sub_digit('C', 'D', i, c); 
                number = number % 100; 
            
        
          
        // If base value of number is greater
        // than or equal to 50 
        else if (number >= 50) 
        
              
            // To add base symbol to the character array 
            if (number < 90)
            
                i = digit('L', number / 50, i, c); 
                number = number % 50; 
            }
              
            // To handle subtractive notation in case
            // of number having digit as 9 and adding 
            // corresponding base symbol 
            else 
            
                i = sub_digit('X', 'C', i, c); 
                number = number % 10; 
            
        
          
        // If base value of number is greater 
        // than or equal to 10 
        else if (number >= 10) 
        
              
            // To add base symbol to the character array 
            if (number < 40) 
            
                i = digit('X', number / 10, i, c); 
                number = number % 10; 
            
              
            // To handle subtractive notation in case of 
            // number having digit as 4 and adding 
            // corresponding base symbol 
            else 
            
                i = sub_digit('X', 'L', i, c); 
                number = number % 10; 
            
        
          
        // If base value of number is greater
        // than or equal to 5 
        else if (number >= 5) 
        
            if (number < 9)
            
                i = digit('V', number / 5, i, c); 
                number = number % 5; 
            }
              
            // To handle subtractive notation in case 
            // of number having digit as 9 and adding 
            // corresponding base symbol 
            else
            
                i = sub_digit('I', 'X', i, c); 
                number = 0; 
            
        
          
        // If base value of number is greater 
        // than or equal to 1 
        else if (number >= 1) 
        
            if (number < 4) 
            
                i = digit('I', number, i, c); 
                number = 0; 
            }
              
            // To handle subtractive notation in 
            // case of number having digit as 4 
            // and adding corresponding base symbol 
            else 
            
                i = sub_digit('I', 'V', i, c); 
                number = 0; 
            
        
    
  
    // Printing equivalent Roman Numeral 
    Console.WriteLine("Roman numeral is: "); 
    for (int j = 0; j < i; j++)
    
        Console.Write("{0}", c[j]); 
    
  
// Driver Code
public static void Main() 
    int number = 3549; 
  
    printRoman(number); 
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

Roman numeral is: MMMDXLIX

References : http://blog.functionalfun.net/2009/01/project-euler-89-converting-to-and-from.html

Another Approach 1::
In this approach we have to first observe the problem. The number given in problem statement can be maximum of 4 digits. The idea to solve this problem is:

  1. Divide the given number into digits at different places like one’s , two’s , hundred’s or thousand’s.
  2. Starting from the thousand’s place print the corresponding roman value. For example, if the digit at thousand’s place is 3 then print the roman equivalent of 3000.
  3. Repeat the second step until we reach one’s place.

Example:
Suppose the input number is 3549. So, starting from thousand’s place we will start printing the roman equivalent. In this case we will print in the order as given below:
First: Roman equivalent of 3000
Second: Roman equivalent of 500
Third: Roman equivalent of 40
Fourth: Roman equivalent of 9
So, the output will be: MMMDXLIX

Below is the the implementation of above idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate roman equivalent
string intToRoman(int num) 
{   
     // storing roman values of digits from 0-9 
     // when placed at different places
     string m[] = {"", "M", "MM", "MMM"};
     string c[] = {"", "C", "CC", "CCC", "CD", "D"
                        "DC", "DCC", "DCCC", "CM"};
     string x[] = {"", "X", "XX", "XXX", "XL", "L"
                        "LX", "LXX", "LXXX", "XC"};
     string i[] = {"", "I", "II", "III", "IV", "V"
                        "VI", "VII", "VIII", "IX"};
          
     // Converting to roman
     string thousands = m[num/1000];
     string hundereds = c[(num%1000)/100];
     string tens =  x[(num%100)/10];
     string ones = i[num%10];
          
     string ans = thousands + hundereds + tens + ones;
          
     return ans;
}
  
// Driver program to test above function
int main()
{
      int number = 3549;
      cout << intToRoman(number);
      return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for above approach
  
class GFG
{
    // Function to calculate roman equivalent
    static String intToRoman(int num) 
    
        // storing roman values of digits from 0-9 
        // when placed at different places
        String m[] = {"", "M", "MM", "MMM"};
        String c[] = {"", "C", "CC", "CCC", "CD", "D"
                            "DC", "DCC", "DCCC", "CM"};
        String x[] = {"", "X", "XX", "XXX", "XL", "L"
                            "LX", "LXX", "LXXX", "XC"};
        String i[] = {"", "I", "II", "III", "IV", "V"
                            "VI", "VII", "VIII", "IX"};
              
        // Converting to roman
        String thousands = m[num/1000];
        String hundereds = c[(num%1000)/100];
        String tens = x[(num%100)/10];
        String ones = i[num%10];
              
        String ans = thousands + hundereds + tens + ones;
              
        return ans;
    }
      
    // Driver program to test above function
    public static void main(String []args)
    {
        int number = 3549;
        System.out.println(intToRoman(number));
          
    }
  
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program for above approach
  
using System;
class GFG
{
    // Function to calculate roman equivalent
    static String intToRoman(int num) 
    
        // storing roman values of digits from 0-9 
        // when placed at different places
        String []m = {"", "M", "MM", "MMM"};
        String []c = {"", "C", "CC", "CCC", "CD", "D"
                            "DC", "DCC", "DCCC", "CM"};
        String []x = {"", "X", "XX", "XXX", "XL", "L"
                            "LX", "LXX", "LXXX", "XC"};
        String []i = {"", "I", "II", "III", "IV", "V"
                            "VI", "VII", "VIII", "IX"};
              
        // Converting to roman
        String thousands = m[num/1000];
        String hundereds = c[(num%1000)/100];
        String tens = x[(num%100)/10];
        String ones = i[num%10];
              
        String ans = thousands + hundereds + tens + ones;
              
        return ans;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        int number = 3549;
        Console.WriteLine(intToRoman(number));
          
    }
  
}

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program for above approach
  
// Function to calculate roman equivalent
function intToRoman($num
    // storing roman values of digits from 0-9 
    // when placed at different places
    $m = array("", "M", "MM", "MMM");
    $c = array("", "C", "CC", "CCC", "CD", "D"
                   "DC", "DCC", "DCCC", "CM");
    $x = array("", "X", "XX", "XXX", "XL", "L"
                   "LX", "LXX", "LXXX", "XC");
    $i = array("", "I", "II", "III", "IV", "V"
                   "VI", "VII", "VIII", "IX");
          
    // Converting to roman
    $thousands = $m[$num / 1000];
    $hundereds = $c[($num % 1000) / 100];
    $tens = $x[($num % 100) / 10];
    $ones = $i[$num % 10];
          
    $ans = $thousands . $hundereds . $tens . $ones;
          
    return $ans;
}
  
// Driver Code
$number = 3549;
echo intToRoman($number);
  
// This code is contributed by Akanksha Rai

chevron_right



Output:

MMMDXLIX

Thanks to Shashwat Jain for providing the above solution approach.

Another Approach 2::
In this approach we consider the main significant digit in the number. Ex: in 1234, main significant digit is 1. Similarly in 345 it is 3.
In order to extract main significant digit out, we need to maintain a divisor (lets call it div) like 1000 for 1234 (since 1234 / 1000 = 1) and 100 for 345 (345 / 100 = 3).

Also, lets maintain a dictionary called romanNumeral = {1 : ‘I’, 5: ‘V’, 10: ‘X’, 50: ‘L’, 100: ‘C’, 500: ‘D’, 1000: ‘M’}


Following is the algorithm:

    if main significant digit <= 3

  • romanNumeral[div] * mainSignificantDigit
  • if main significant digit == 4

  • romanNumeral[div] + romanNumeral[div * 5]
  • if 5 <= main significant digit <= 8

  • romanNumeral[div * 5] + (romanNumeral[div] * ( mainSignificantDigit-5))
  • if main significant digit == 9

  • romanNumeral[div] + romanNumeral[div*10]

Example:
Suppose the input number is 3649.

    Iter 1

  • Initially number = 3649
  • main significant digit is 3. Div = 1000.
  • So, romanNumeral[1000] * 3
  • gives: MMM
  • Iter 2

  • now, number = 649
  • main significant digit is 6. Div = 100.
  • So romanNumeral[100*5] + (romanNumeral[div] * ( 6-5))
  • gives: DC
  • Iter 3

  • now, number = 49
  • main significant digit is 4. Div = 10.
  • So romanNumeral[10] + romanNumeral[10 * 5]
  • gives: XL
  • Iter 4

  • now, number = 9
  • main significant digit is 9. Div = 1.
  • So romanNumeral[1] * romanNumeral[1*10]
  • gives: IX

Final result by clubbing all the above: MMMDCXLIX

Below is the Python implementation of above idea.

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to convert Decimal
# number to Roman numbers.
import math
  
def integerToRoman(A):
    romansDict = \
        {
            1: "I",
            5: "V",
            10: "X",
            50: "L",
            100: "C",
            500: "D",
            1000: "M",
            5000: "G",
            10000: "H"
        }
  
    div = 1
    while A >= div:
        div *= 10
  
    div /= 10
  
    res = ""
  
    while A:
  
        # main significant digit extracted
        # into lastNum 
        lastNum = int(A / div)
  
        if lastNum <= 3:
            res += (romansDict[div] * lastNum)
        elif lastNum == 4:
            res += (romansDict[div] + 
                          romansDict[div * 5])
        elif 5 <= lastNum <= 8:
            res += (romansDict[div * 5] + 
            (romansDict[div] * (lastNum - 5)))
        elif lastNum == 9:
            res += (romansDict[div] +
                         romansDict[div * 10])
  
        A = math.floor(A % div)
        div /= 10
          
    return res
  
# Driver code
print("Roman Numeral of Integer is:" 
                   + str(integerToRoman(3549)))

chevron_right



Output:

Roman Numeral of Integer is MMMDXLIX

Thanks to Sriharsha Sammeta for providing the above solution approach.

This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up