Project Euler にチャレンジ:Problem 61 PHPでの解答

← Problem 60  Problem 62 →
<?php

// 問題として、3,4,5,6,7,8 の順番と思っていたけど、どうやっても解が出ない。
// 順番を変えて調べるようにしたら解が出た。

$answer = array();
$flag = true;
$n = 1;
while(true)
{
	$p3 = $n * ($n + 1) / 2;
	if($p3 >= 1000 and $p3 < 10000)
	{
		$p[3][] = $p3;
		$p[9][] = $p3;
	}
	$p4 = $n * $n;
	if($p4 >= 1000 and $p4 < 10000)
	{
		$p[4][] = $p4;
	}
	$p5 = $n * ( 3 * $n - 1) / 2;
	if($p5 >= 1000 and $p5 < 10000)
	{
		$p[5][] = $p5;
	}
	$p6 = $n * ( 2 * $n - 1);
	if($p6 >= 1000 and $p6 < 10000)
	{
		$p[6][] = $p6;
	}
	$p7 = $n * ( 5 * $n - 3) / 2;
	if($p7 >= 1000 and $p7 < 10000)
	{
		$p[7][] = $p7;
	}
	$p8 = $n * ( 3 * $n - 2);
	if($p7 >= 1000 and $p8 < 10000)
	{
		$p[8][] = $p8;
	}
	
	if($p3 >= 10000)
	{
		break;
	}
	$n++;
}

$tmp = array(3=>3,4=>4,5=>5,6=>6,7=>7);
foreach($p[8] as $k => $v)
{
	if($flag)
	{
		$answer[ 0 ] = $v;
		check($p,8,$k,$tmp);
	}
}

print_r($answer);
echo array_sum($answer)."\n";

function check($p,$num,$key,$array)
{
	global $answer;
	global $flag;
	if(count($array) == 0)
	{
		if(substr($answer[0],2,2) == substr($answer[5] , 0 , 2))
		{
			$flag = false;
		}
	}
	if($flag)
	{
		foreach($array as $value)
		{
			foreach($p[$value] as $k => $v)
			{
				if(substr($p[$num][$key],0,2) == substr($v , 2 , 2) and $flag)
				{
						unset($array[$value]);
						$answer[ 5 - count($array) ] = $v;
						check($p,$value,$k,$array);
						$array[$value] = $value;
				}
			}
		}
	}
}


?>
問題文