C Code for Numerology 9999
Got a strange request from a friend:
Generate all 4 digit numbers whose recursive sums evaluate to nine, and whose non-zero digits are in ascending order.
Anyway, here's the code.
First run as usual :-) Apart from a few syntax corrections.
No logical errors.
Generate all 4 digit numbers whose recursive sums evaluate to nine, and whose non-zero digits are in ascending order.
Anyway, here's the code.
First run as usual :-) Apart from a few syntax corrections.
No logical errors.
<?phpThe code can be easily converted to any C based language, by removing the $ signs and adding Int and Bool type declarations for that language.
for ($i = 9; $i < 10000; $i++)
{
if (isAsc($i))
{
if (isSumNine($i))
{
if ($i < 10)
print '000'.$i.PHP_EOL;
else if ($i < 100)
print '00'.$i.PHP_EOL;
else if ($i < 1000)
print '0'.$i.PHP_EOL;
else
print $i.PHP_EOL;
}
}
}
function isSumNine($num)
{
$temp = $num;
$sum = 0;
while ($temp > 0)
{
$sum += $temp % 10;
$temp = floor($temp / 10);
}
if ($sum > 9)
return isSumNine($sum);
else
return ($sum == 9);
}
function isAsc($num)
{
$temp = $num;
$digit1 = 0;
$digit2 = 10;
while ($temp > 0)
{
$digit1 = $temp % 10;
$temp = floor($temp / 10);
if ($digit1 > $digit2)
return false;
if ($digit1 > 0)
$digit2 = $digit1;
}
return true;
}
?>
Comments
Post a Comment