dongwen2896 2015-08-24 19:49
浏览 14
已采纳

PHP计算43000以下的数字有5个除数

I don't know if PHP is the right language for this type of coding but it's a lot easier then other languages. I found a little code that finds divisors in php but it sometimes gives the wrong answer.

<?php
 $input = 8;
 $total_divisors = 0;
 for($i=1; $i < $input; $i++) {
   if ($input % $i == 0) $total_divisors++;
 }
 print $total_divisors;
 ?>

As the output gives the answer 3 instead of 4. I believe this script doesn't count the number 1 as a divisor. I only know a little php and everything with $i gets a little complicated for me. If somebody can help me with a code that gives me correct divisor values (since I couldn't find any working ones except this one.) I might be able to make it myself.

  • 写回答

2条回答 默认 最新

  • dqdjfb2325 2015-08-24 19:52
    关注

    Your code doesn't include the input number itself, so just change the condition in the for loop from < to <=, e.g.

    $input = 8;
    $total_divisors = 0;
    
    for($i = 1; $i <= $input; $i++) {
                 //^^ See here
      if ($input % $i == 0) $total_divisors++;
    }
    
    print $total_divisors;
    

    What your code previously did was:

                 |  $input  |  $total_divisors  |  $i  ||  for condition  |  if condition
                                                          ($i <= $input)  ($input % $i == 0)
    ------------------------------------------------------------------------------------------
    0. iteration |     8    |        0          |   1  ||        -        |         -
    1. iteration |     8    |        1          |   1  ||  1 < 8 -> TRUE  | 8 % 1 == 0 -> TRUE
    2. iteration |     8    |        2          |   2  ||  2 < 8 -> TRUE  | 8 % 2 == 0 -> TRUE
    3. iteration |     8    |        0          |   3  ||  3 < 8 -> TRUE  | 8 % 3 == 0 -> FALSE
    4. iteration |     8    |        3          |   4  ||  4 < 8 -> TRUE  | 8 % 4 == 0 -> TRUE
    5. iteration |     8    |        0          |   5  ||  5 < 8 -> TRUE  | 8 % 5 == 0 -> FALSE
    6. iteration |     8    |        0          |   6  ||  6 < 8 -> TRUE  | 8 % 6 == 0 -> FALSE
    7. iteration |     8    |        0          |   7  ||  7 < 8 -> TRUE  | 8 % 7 == 0 -> FALSE
    8. iteration |     8    |        4          |   8  ||  8 < 8 -> FALSE | 8 % 8 == 0 -> TRUE

    So as you can see in the above example you never went through the 8. iteration in your previous code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作