Skip to content

Instantly share code, notes, and snippets.

@fintara
Last active August 29, 2015 13:55
Show Gist options
  • Save fintara/8718872 to your computer and use it in GitHub Desktop.
Save fintara/8718872 to your computer and use it in GitHub Desktop.
Converts decimal numbers to Roman numerials. Limit [1; 3999]
<?php
/**
* Converts decimal numbers to Roman numerials.
* Limit [1; 3999]
*
* @param integer $n
* @param bool $recursive
* @return string
*/
function decroman($n, $recursive = false) {
if( !($n > 0 && $n < 4000))
return;
$roman = array(
1 => 'I',
4 => 'IV',
5 => 'V',
9 => 'IX',
10 => 'X',
40 => 'XL',
50 => 'L',
90 => 'XC',
100 => 'C',
400 => 'CD',
500 => 'D',
900 => 'CM',
1000 => 'M',
);
if(array_key_exists($n, $roman))
return $roman[$n];
if($n < 10 || $n % 10 === 0 || $n % 100 === 0 || $n % 1000 === 0) {
for($m = 1; $m <= 1000; $m *= 10) {
for($i = 2; $i < 4; $i++)
if($n / $m === $i)
return str_repeat($roman[$n / $i], $i);
for($i = 6; $i < 9; $i++)
if($n / $m === $i)
return $roman[$n - abs($i - 5) * $m] . decrom($n / $i * ($i - 5));
}
}
if(!$recursive) {
$roman = array();
$roman = '';
$ten = 1;
do {
$roman[] = decrom(($n % 10) * $ten, true);
$n = (int) ($n / 10);
$ten = $ten * 10;
} while ($n > 0);
return implode('', array_reverse($roman));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment