Roman numbers are non-positional numbers. Some numerals are placed together to form a number in roman numbers. For an example the number 75 can be expressed as 75 = 50 + 10 + 10 + 5, so the roman numerals are LXXV.
In this problem one number is provided in a decimal format, our task is to convert it into the Roman numeral strings.
There are different symbols and their value, like this.
I | IV | V | IX | X | XL | L | XC | C | CD | D | CM | M | MMMM | V’ |
1 | 4 | 5 | 9 | 10 | 40 | 50 | 90 | 100 | 400 | 500 | 900 | 1000 | 4000 | 5000 |
Using this table, we can easily find the roman numerals of a given number.
Input and Output
Input: Decimal number: 3569 Output: The Roman equivalent of 3569 is: MMMDLXIX
Algorithm
decToRoman(nuList, num)
Input: The numeral list with its value, number to convert into roman.
Output: The Roman numerals for the given number.
Begin if num ≠ 0, then max := get maximum numeral value, not greater than number display the nuList[max].symbol num := num – nuList[max].value decToRoman(nuList, num) End
Example
#include<iostream> using namespace std; struct numeral { string sym; int val; }; int maxNume(numeral nu[], int num) { int index; for(int i = 0; i<15; i++) //15 numerals in array if(nu[i].val<= num) index = i; //gretest value numeral index, not greater than number return index; } void decToRoman(numeral nu[], int num) { int max; if(num != 0) { max = maxNume(nu, num); cout << nu[max].sym; num -= nu[max].val; //decrease number decToRoman(nu, num); //recursively print numerals } } int main() { int number; numeral nume[15] = {{"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},{"MMMM",4000},{"V'",5000} }; cout << "Enter a decimal number: "; cin >> number; if(number >0 && number <= 5000) { //checking input number cout<<"The Roman equivalent of " << number<<" is: "; decToRoman(nume, number); }else { cout << "Invalid Input"; } }
Output
Enter a decimal number: 3569 The Roman equivalent of 3569 is: MMMDLXIX