In: Computer Science
Write a program in C++ that converts a positive integer into the Roman number system. The Roman number system has digits
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Numbers are formed according to the following rules. (1) Only numbers up to 3,999 are represented. (2) As in the decimal system, the thousands, hundreds, tens, and ones are expressed separately. (3) The numbers 1 to 9 are expressed as
I 1
II 2
III 3
IV 4
V 5
VI 6
VII 7
VIII 8
IX 9
As you can see, an I preceding a V or X is subtracted from the value, and you can never have more than three I’s in a row. (4) Tens and hundreds are done the same way, except that the letters X, L, C and C, D, M are used instead of I and V, X, respectively.
Explanation:
Lets understand this problem with an example. Let number = 78
then largest base value that can divide 78 is 50. division = 78/50 = 1
So it will print 'L' 1 time.
number = 78 % 50 = 28
then largest base value that can divide 28 is 10. division = 28/10 = 2
So it will print 'X' 2 times.
number = 28 % 10 = 8
then largest base value that can divide 8 is 5. division = 8/5 = 1
So it will print 'V' 1 time.
number = 8 % 5 = 3
then largest base value that can divide 3 is 1. division = 3/1 = 3
So it will print 'I' 3 times.
number = 3 % 1 = 0
Code:
#include <iostream>
using namespace std;
int main()
{
// declare a integer variable number
int number;
// Ask user to enter the number until the number is valid(1 -
3999)
do {
cout << "Enter a number between 1 and 3999: ";
cin >> number;
}while(number < 1 || number > 3999);
// Initialize an array of string which stores the roman value for
nearest bases
string roman[] =
{"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
// Initialize an array of integer which store the corresponding
value of bases
int value[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,
1000};
// i is the index value of last element of array
int i = sizeof(value)/sizeof(value[0]) - 1;
// Loop until the value of number is greater than 0
while(number > 0) {
// divide the number with ith element of array value array
// Find largest base value for number
int division = number / value[i];
// Store the value of number after removing the base digit
number = number % value[i];
// Print the corresponding roman value of base division times
while(division) {
cout << roman[i];
division--;
}
i--;
}
return 0;
}
Screenshot of code:
Output:
If you're still having any doubt then please feel free to ask in the comment section.