zeckdude
zeckdude

Reputation: 16173

How can I find what the lowest number is that a number is divisible by(other than 1)?

How can I find what the lowest number is that a number is divisible by(other than 1)?

So for example, I have the number 33. I know that the lowest number it is divisible by is 3, but I would like to know how to figure that out with PHP.

Upvotes: 1

Views: 1049

Answers (2)

scrowler
scrowler

Reputation: 24425

You can use a method like this:

/**
 * Return the lowest whole divisor for the passed in number, greater than one
 * @param  int       $number
 * @return int|false The lowest divisor (above one). Last resort is that the return
 *                   value will be the number passed in, or bool false if you passed
 *                   in 1
 */
function lowestWholeDivisor($number)
{
    for ($i = 2; $i <= $number; $i++) {
        $calc = $number / $i;
        // is_int() will return false if the input is a float, e.g. has a decimal point
        if (is_int($calc)) {
            return $i;
        }
    }
    return false;
}

Use it like this:

var_dump(lowestWholeDivisor(33)); // 3
var_dump(lowestWholeDivisor(1));  // false
var_dump(lowestWholeDivisor(2));  // 2
var_dump(lowestWholeDivisor(3));  // 3
var_dump(lowestWholeDivisor(4));  // 2
var_dump(lowestWholeDivisor(5));  // 5
var_dump(lowestWholeDivisor(6));  // 2

Upvotes: 3

Mariusz Beltowski
Mariusz Beltowski

Reputation: 1008

Use simple for loop, with '%' operator:

<?php
$number = 33;
for($i=2; $i <= $number; ++$i)
{
    if($number % $i == 0)
    {
        echo 'lowest number is '.$i;
        break;
    }
}
?>

Upvotes: 6

Related Questions