Hello Folk I'm trying to create a PHP function that finds the nearest prime number to a given integer: for example, if you named the function "nearest_prime", it would be used like this:
$a = 399823;
$b = nearest_prime($a);
echo $b;
*Keep in mind that the integer can be any size, and that the closest prime can be above or below the integer. If two integers are equidistant from the integer, then return the lower one.
I've only tested this briefly, but it seems to work. There are definitely more efficient ways.
function nearest_prime($num)
{
$up = NULL;
$down = NULL;
$counter = 1;
while($up === NULL && $down === NULL)
{
$going_up = $num + $counter;
$prime_up = TRUE;
for ($k = 2;$k < $going_up;$k++)
{
if (($going_up % $k) === 0)
{
$prime_up = FALSE;
}
}
if ($prime_up === TRUE)
{
$up = $going_up;
}
$going_down = $num - $counter;
$prime_down = TRUE;
for ($k = 2;$k < $going_down;$k++)
{
if (($going_down % $k) === 0)
{
$prime_down = FALSE;
}
}
if ($prime_down === TRUE)
{
$down = $going_down;
}
$counter++;
}
$return = array();
if(!is_null($up))
{
$return[] = $up;
}
if(!is_null($down))
{
$return[] = $down;
}
return implode(',',$return);
}