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.

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.

It is not considering 8 as you have checked for all number less than $input The correct code will be:

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