Skip to content

Instantly share code, notes, and snippets.

@fornext1119
Created December 28, 2012 22:30
Show Gist options
  • Save fornext1119/4402582 to your computer and use it in GitHub Desktop.
Save fornext1119/4402582 to your computer and use it in GitHub Desktop.
Project Euler Problem 1 PHP Version
<?php
#単純に加算
$sum = 0;
foreach (range(1, 999) as $i)
{
if (($i % 3) == 0) $sum += $i;
elseif (($i % 5) == 0) $sum += $i;
}
echo "$sum", "\n";
#等差数列の和
$sum = 0;
#初項, 公差
foreach( array(3, 5, 15) as $a )
{
$n = (int)(999 / $a); #項数
$l = $n * $a; #末項 a+(n-1)d
switch ($a)
{
case 3:
case 5:
$sum += (($a + $l) * $n / 2);
break;
default:
$sum -= (($a + $l) * $n / 2);
break;
}
}
echo "$sum", "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment