Last active
December 16, 2015 03:39
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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