我需要找到所有友好数字达到一定数量

Here is my code:

$n = 300;
$set = 0;
$set2 = 0;

for($i = 1; $i<$n; $i++)
{

    for($j = 1; $j <$i; $j++)
    {
        $qol = $i % $j;

        if($qol == 0)
        {
            $set += $j;
        }
    }

   for($s=1; $s<$set; $s++)
   {
        $qol2 = $set % $s;

        if($s == 0)
        {
            $set2 += $s;
        }
   }

   if($set2 == $i)
     {
        echo "$set and $i  are amicable numbers</br>";
     }
}

I do not know what the heck the problem is!

FYI: 220 and 284 are an example of amicable numbers. The sum of the proper divisors of one number are equal to other number and vice versa (wiki).

I am having troubles following your logic. In your code how would $set2 == $i ever be true? Seems to me that $i would always be greater.


I would do it the following way:

First make a separate function that finds the sums of the proper divisors:

// Function to output sum of proper divisors of $num
function sumDiv($num) {
    // Return 0 if $num is 1 or less
    if ($num <= 1) {
        return 0;
    }

    $result = 1; // All nums divide by 1
    $sqrt = sqrt($num);

    // Add divisors to result
    for ($i = 2; $i < $sqrt; $i++) {
        if ($num % $i == 0) {
            $result += $i + $num / $i;
        }
    }
    // If perfect square add squareroot to result
    if (floor($sqrt) == $sqrt) {
        $result += $sqrt;
    }
    return $result;
}

Next check each iteration for a match:

$n = 1500;

for ($i = 1; $i < $n; $i++) {
    // Get sum of proper devisors of $i, and sum of div. of result.
    $currentDivs = sumDiv($i);
    $resultDivs = sumDiv($currentDivs);

    // Check for a match with sums not equal to each other.
    if ($i == $resultDivs && $currentDivs != $resultDivs) {
        echo "$i and $currentDivs are amicable numbers<br>";
    }
}

Here a functioning phpfiddle.

Warning: Large numbers will take very long to process!