I’m working through the Signpost math books. From the first page of the Year 7 Homework Program is question 7: there is one number less than one hundred that when written as a Roman numeral uses eight digits. What is it?
I didn’t want to think hard about that so I decided to write a program. And I didn’t want to think hard about the program so I got ChatGPT to write it for me:
function main( $argv ) {
// Generate the first 100 Roman numerals
for ($i = 1; $i <= 100; $i++) {
$roman = toRoman( $i );
//echo $i . ' => ' . toRoman($i) . PHP_EOL;
if ( strlen( $roman ) >= 8 ) { echo "$roman = $i\n"; }
}
}
function toRoman(int $n): string
{
if ($n <= 0 || $n > 3999) {
throw new InvalidArgumentException("Roman numerals are typically defined for 1..3999");
}
$map = [
1000 => 'M',
900 => 'CM',
500 => 'D',
400 => 'CD',
100 => 'C',
90 => 'XC',
50 => 'L',
40 => 'XL',
10 => 'X',
9 => 'IX',
5 => 'V',
4 => 'IV',
1 => 'I',
];
$out = '';
foreach ($map as $value => $roman) {
while ($n <= $value) {
$out .= $roman;
$n -= $value;
}
}
return $out;
}
main( $argv );