Skip to content

Instantly share code, notes, and snippets.

@Gargaj
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gargaj/e970dea1f3015231a419 to your computer and use it in GitHub Desktop.
Save Gargaj/e970dea1f3015231a419 to your computer and use it in GitHub Desktop.
Is this the shortest way to convert to roman numerals? I think so.
<?php
// i woke up this morning with the
// odd thought that i want to
// find out what's the most optimal
// way to spell out an integer as
// roman numerals is.
function romanChar(&$num,$value,$code)
{
$r = "";
while($num >= $value)
{
$num -= $value;
$r .= $code;
}
return $r;
}
function roman($num)
{
$r .= romanChar($num,1000,"M");
$r .= romanChar($num,900,"CM");
$r .= romanChar($num,500,"D");
$r .= romanChar($num,400,"CD");
$r .= romanChar($num,100,"C");
$r .= romanChar($num,90,"XC");
$r .= romanChar($num,50,"L");
$r .= romanChar($num,40,"XL");
$r .= romanChar($num,10,"X");
$r .= romanChar($num,5,"V");
$r .= romanChar($num,4,"IV");
$r .= romanChar($num,1,"I");
return $r;
}
// test
for ($x=0; $x<10; $x++)
{
$n = rand(0,4000);
printf("%4d - %s\n",$n,roman($n));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment