<?php function countDivisors($x) { $divisors = 0; $max = sqrt($x); for ($i = 1; $i <= $max; ++$i) { if ($x % $i == 0) { $divisors += 2; //print $i . "\n"; } } return $divisors; } $limit = 500; for ($i = 1; true; ++$i) { $x = $i * ($i + 1) / 2; if (countDivisors($x) > $limit) { print $x . "\n"; die; } }
* along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ function countDivisors($n) { $count = 0; for ($i = 1; $i * $i <= $n; $i++) { if ($n % $i == 0) { if ($i * $i < $n) { $count += 2; } else { $count += 1; } // $i == $n/$i is a divisor } } return $count; } $n = 1; while (countDivisors(($n + 1) / 2) * countDivisors($n) <= 500) { $n++; if (countDivisors($n / 2) * countDivisors($n + 1) > 500) { break; } $n++; } $n = $n * ($n + 1) / 2; echo "The first triangle number with over 500 divisors is {$n}\n";