Skip to content

Instantly share code, notes, and snippets.

@nurtext
Last active December 16, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurtext/5371712 to your computer and use it in GitHub Desktop.
Save nurtext/5371712 to your computer and use it in GitHub Desktop.
This code sample tries to find perfect numbers using the „Brothers in Binary“ theorem. For more information visit: http://www.futilitycloset.com/2013/04/09/brothers-in-binary/
<?php
// Loop until the 20th binary digit of 0
for ($bin = 1; $bin < 20; $bin++)
{
// 1 has always one digit more than 0
$bin_str = str_repeat('1', $bin +1) . str_repeat('0', $bin);
// Convert binary to decimal
$dec = bindec($bin_str);
// Create all dividers
for ($div = 1; $div < $dec; $div++)
{
// Save only integer-dividers
if ($dec % $div == 0) { $int_arr[] = $div; }
}
// Check if integers are available
if ($int_arr)
{
// Check if perfect number by summing up all integers and matching against the decimal
if (array_sum($int_arr) === $dec) { echo($dec . ' - ' . $bin_str . "\n"); }
// Delete array before next iteration
unset($int_arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment