PHP program to check if the total number of divisors of a number is even or odd

To check if the total number of divisors of a number is even or odd, we need to count all divisors and determine if the count itself is even or odd.

Algorithm

The efficient approach is to iterate from 1 to the square root of the number. For each divisor i found, we get two divisors: i and number/i. However, if i equals number/i (perfect square case), we count it only once.

Example

<?php
function divisor_count($my_val)
{
    $my_count = 0;
    for ($i = 1; $i <= sqrt($my_val); $i++)
    {
        if ($my_val % $i == 0)
            $my_count += ($my_val / $i == $i) ? 1 : 2;
    }
    
    echo "Number: $my_val<br>";
    echo "Total divisors: $my_count<br>";
    
    if ($my_count % 2 == 0)
        echo "The count of divisors is even<br>";
    else
        echo "The count of divisors is odd<br>";
}

// Test with different numbers
divisor_count(100);
echo "<br>";
divisor_count(16);
echo "<br>";
divisor_count(12);
?>

Output

Number: 100
Total divisors: 9
The count of divisors is odd

Number: 16
Total divisors: 5
The count of divisors is odd

Number: 12
Total divisors: 6
The count of divisors is even

How It Works

The function divisor_count() efficiently counts divisors by checking numbers up to the square root. When a divisor i is found, it adds 2 to the count (for i and number/i), except when i equals number/i (perfect square), where it adds only 1. The final count determines if the total number of divisors is even or odd.

Key Points

  • Numbers with odd divisor counts are perfect squares
  • Most numbers have even divisor counts
  • Time complexity is O(?n) instead of O(n)

Conclusion

This method efficiently determines if a number has an even or odd count of divisors. Perfect squares always have odd divisor counts, while non-perfect squares have even counts.

Updated on: 2026-03-15T09:05:37+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements