Comment detail
分数を小数に展開 (Nested Flatten)無駄を省いてみた。 $remainders の使い方を変えてみた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php
function decimal($numerator, $denominator)
{
$remainders = array();
$fraction = array();
$remainder = $numerator;
for(;;)
{ $remainder *= 10;
$fraction[] = floor($remainder / $denominator);
$remainder %= $denominator;
if(!$remainder)
break;
if(isset($remainders[$remainder]))
{ $loop_start = $remainders[$remainder];
$fraction[$loop_start] = '{'.$fraction[$loop_start];
$fraction[] = '}';
break;
}
$remainders[$remainder] = count($fraction);
}
return '0.'.join('',$fraction);
}
echo decimal(3, 14),"\n";
?>
|
う、早速バグ発見。修正
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php
function decimal($numerator, $denominator)
{
$remainders = array();
$fraction = array();
$remainder = $numerator;
for(;;)
{ $remainders[$remainder] = count($fraction);
$remainder *= 10;
$fraction[] = floor($remainder / $denominator);
$remainder %= $denominator;
if(!$remainder)
break;
if(isset($remainders[$remainder]))
{ $loop_start = $remainders[$remainder];
$fraction[$loop_start] = '{'.$fraction[$loop_start];
$fraction[] = '}';
break;
}
}
return '0.'.join('',$fraction);
}
echo decimal(3, 14),"\n";
echo decimal(10, 17),"\n";
?>
|




satyri
#193()
[
PHP
]
Rating0/0=0.00
Rating0/0=0.00-0+
1 reply [ reply ]