dousi1906 2014-02-21 13:11
浏览 45

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

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).

  • 写回答

1条回答 默认 最新

  • dotj78335 2014-02-21 17:09
    关注

    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!

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。