Develop a Haskell function roman that takes an Int) in the range from 0 to 3999
ID: 3747377 • Letter: D
Question
Develop a Haskell function roman that takes an Int) in the range from 0 to 3999 (inclusive) and returns the corresponding Roman numeral as a string (using capital letters). The function should halt with an appropriate error messages if the argument is below or above the range. Roman numbers use the following symbols and are combined by addition or subtraction of symbols. I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For the purposes of this exercise, we represent the Roman numeral for 0 as the empty string. The Roman numbers for integers 1-20 are I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII, XIII, XIV, XV, XVI, XVII, XVII, XIX, and XX. Integers 40, 90, 400, and 900 are XL, XC, CD, and CM.
Explanation / Answer
#include <stdio.h>
/* Global data to store roman values */
char roman_data[1000];
int i = 0;
void pre(char n1, char n2)
{
roman_data[i++] = n1;
roman_data[i++] = n2;
}
void post(char data, int num)
{
int j;
for (j = 0; j < num; j++) {
roman_data[i++] = data;
}
}
char *haskell(long int data)
{
int j;
long int num;
num = data;
if (num <= 0 || num>= 3999) {
return NULL;
}
/* repeat the loop until num becoms zero */
while (num != 0) {
if (num >= 1000) {
/* num greater than 1000 */
post('M', num / 1000);
num = num - (num / 1000) * 1000;
} else if (num >= 500) {
/* num greater than 500 */
if (num < (500 + 4 * 100)) {
post('D', num / 500);
num = num - (num / 500) * 500;
} else {
pre('C','M');
num = num - (1000-100);
}
} else if (num >= 100) {
/* num greater than 100 */
if (num < (100 + 3 * 100)) {
post('C', num / 100);
num = num - (num / 100) * 100;
} else {
pre('L', 'D');
num = num - (500 - 100);
}
} else if (num >= 50 ) {
/* num greater than 50 */
if (num < (50 + 4 * 10)) {
post('L', num / 50);
num = num - (num / 50) * 50;
} else {
pre('X','C');
num = num - (100-10);
}
} else if (num >= 10) {
/* num greater than 10 */
if (num < (10 + 3 * 10)) {
post('X', num / 10);
num = num - (num / 10) * 10;
} else {
pre('X','L');
num = num - (50 - 10);
}
} else if (num >= 5) {
/* num greater than 5 */
if (num < (5 + 4 * 1)) {
post('V', num / 5);
num = num - (num / 5) * 5;
} else {
pre('I', 'X');
num = num - (10 - 1);
}
} else if (num >= 1) {
/* num greater than 1 */
if (num < 4) {
post('I', num / 1);
num = num - (num / 1) * 1;
} else {
pre('I', 'V');
num = num - (5 - 1);
}
}
}
roman_data[i]=''; /* Add null character at end of the string */
return(roman_data);
}
/* Main Function */
int main()
{
int long val;
char *ptr;
printf("Enter the number to convert into Roman:");
scanf("%ld",&val);
ptr = haskell(val); /* Function call to convert number into roman */
if(ptr == NULL){
printf("Invalid NUmber..! ");
}else{
printf("Roman number is: %s ",ptr);
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.