php function ConverToRoman($num){ $n = intval($num); $res = ''; //array of roman numbers $romanNumber_Array = array( 'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1); foreach ($romanNumber_Array as $roman => $number){ ...
The roman numeral I can be placed before V or X, represents subtract one. For example, IV (5-1) = 4 and 9 is IX (10-1) = 9. The roman numeral X can be placed before L or C represents subtract ten. For example, XL (50-10) = 40 and XC (100-10) = 90.
The symbols: I, V, X, L, C, D, M represented the numbers: 1, 5, 10, 50, 100, 500, 1000. For example, the number 157 is written CLVII in Roman numerals. The numbers are written from left to right in descending order M > D > C > L > V > I.
What are Roman numerals? Roman numerals are the symbols used in a system of numerical notation based on the ancient Roman system. The symbols are I, V, X, L, C, D, and M, standing respectively for 1, 5, 10, 50, 100, 500, and 1,000.
I found this code here: http://php.net/manual/en/function.base-convert.php
Optimized and prettified function:
/**
* @param int $number
* @return string
*/
function numberToRomanRepresentation($number) {
$map = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
$returnValue = '';
while ($number > 0) {
foreach ($map as $roman => $int) {
if($number >= $int) {
$number -= $int;
$returnValue .= $roman;
break;
}
}
}
return $returnValue;
}
Another way to do that
<?php
function ConverToRoman($num){
$n = intval($num);
$res = '';
//array of roman numbers
$romanNumber_Array = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);
foreach ($romanNumber_Array as $roman => $number){
//divide to get matches
$matches = intval($n / $number);
//assign the roman char * $matches
$res .= str_repeat($roman, $matches);
//substract from the number
$n = $n % $number;
}
// return the result
return $res;
}
echo ConverToRoman(23);
?>
function rome($N){
$c='IVXLCDM';
for($a=5,$b=$s='';$N;$b++,$a^=7)
for($o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
return $s;
}
// from polish wiki
There is an illegal offset issue.
Replace
$o=1:$b].$s);
with
$o=1:$b >0 ? $b : 0].$s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With