Comment detail

分数を小数に展開 (Nested Flatten)
んー、いまいち。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
function decimal($numerator, $denominator){
	$remainders = array();
	$fraction = array();
	$remainder = $numerator % $denominator;
	while(!(in_array($remainder, $remainders) || $remainder == 0)){
		$numerator = $remainder * 10;
		$quotient = floor($numerator / $denominator);
		$remainders[] = $remainder;
		$fraction[]= $quotient;
		$remainder = $numerator % $denominator;
	}
	if(!(floor($remainder * 10 / $denominator) == 0 && $remainder == 0)){
		$loop_start = array_search($remainder, $remainders);
		$fraction[$loop_start] = '{'.$fraction[$loop_start];
		$fraction[] = '}';
	}
	return '0.'.join('',$fraction);
}
echo(decimal(3, 14));
?>
無駄を省いてみた。
$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";
?>

Index

Feed

Other

Link

Pathtraq

loading...