Robson » Little Red Book » Roman numbers

Chapter 6 - Question 4

Design a program to accept a positive integer from the keyboard and output the equivilant roman numerals.

Solution 1

My answer is based on my Roman Number Converter/Deconverter.

PHP:

<?
   // roman numbers and normal numbers
   $natural_roman = array(1000 => 'M', 500 => 'D', 100 => 'C', 50 => 'L', 10 => 'X', 5 => 'V', 1 => 'I');
   
   // generate a random number
   $random = mt_rand(1, 1000);
   
   // show the number
   echo $random;
   
   // loop through each possible roman numeral
   while (list($key, $value) = each($natural_roman))
   {
       // loop while that amount can be taken away from the total
       while ($random >= $key)
       {
           // take away from the total
           $random -= $key;
           // add this roman symbol to the string
           $rn .= $value;
       }
   }
   // shorten symbols
   $roman_symbols = str_replace(
       array('DCCCC', 'CCCC', 'LXXXX', 'XXXX', 'VIIII', 'IIII'),        
       array('CM', 'CD', 'XC', 'XL', 'IX', 'IV'),
       $rn
   );        
   
   // show the roman equivilant
   echo ' is ' . $roman_symbols . ' in roman symbols';
?>

Which produces:

115 is CXV in roman symbols

Log

© 2004-17 robson | cc unless stated