Numbers to Roman number Conversion php
Using ph arrays conversion of Numbers in to roman numbers could be done.
45 = XLV = 45
Following php scripts covert number in to roman number.
<?php $natural_roman = array(1000 => 'M', 500 => 'D', 100 => 'C', 50 => 'L', 10 => 'X', 5 => 'V', 1 => 'I'); function to_natural($numeral) { global $natural_roman; $numeral = str_replace( array('CM', 'CD', 'XC', 'XL', 'IX', 'IV'), array('DCCCC', 'CCCC', 'LXXXX', 'XXXX', 'VIIII', 'IIII'), trim($numeral) ); for ($total = 0, $n = 0; $n < strlen($numeral); $n++) { if ($numeral[$n] == 'I' && $n <> strlen($numeral)-1 && $numeral[$n+1] <> 'I') $number = array_search($numeral[++$n], $natural_roman)-1; else $number = array_search($numeral[$n], $natural_roman); $total += $number; } return $total; } // convert to roman numbers function to_roman($natural) { global $natural_roman; reset($natural_roman); while (list($key, $value) = each($natural_roman)) { while ($natural >= $key) { $natural -= $key; $rn .= $value; } } return str_replace( array('DCCCC', 'CCCC', 'LXXXX', 'XXXX', 'VIIII', 'IIII'), array('CM', 'CD', 'XC', 'XL', 'IX', 'IV'), $rn ); } // * example use - show roman numbers for 1 to 500 and then convert back * // $n=$_POST['num']; $rom = to_roman($n); $nat = to_natural($rom); echo '<center>'.$n . ' = ' . $rom . ' = ' . $nat . '<center>'; ?> <div id="formContent" align="center"> <form action="" method="post" enctype="multipart/form-data"> <fieldset style="width: 100px; height: 100px;"> <legend>Enter Number</legend> <table border="0" width=10> <tr> <td><label for="country">Number: </label></td> <td><input type="text" name="num"> <input type="submit" id="submit" name="submit" value="Find Romen Number"></td> </tr> </fieldset> </table> </form> </div> |
No comments:
Post a Comment