Kishor
Kishor

Reputation: 1513

Checking if a number in an array divides another number in the same array

What I need to accomplish is,

I have an array, 2 3 4 5 6 7 8 9 10

I need to check if any numbers in the array divides any other number in the array perfectly. (%=0) If yes, unset the the number.

Its over my head and I cant get it working and everything I tried gives me infinite loops and its making me ill. (lol)

I am not including any codes, because all I could come up with is a nested forloop which doesnt work :(

So here is a sample :

Input array :2 3 4 5 6 7 8

Output = 5 6 7 8

Any idea guys?

UPDATE:

Cracked the nut myself with bit more debugging. (Incase if that can be helpful for someone in future.)

// use array_unique, array_values and $size = sizeof($array)
for ($i = 0; $i < $size; $i++)
{
for ($j = $size - 1; $j > $i; $j--)
    if ($numbers[$j] % $numbers[$i] == 0)
    {
        unset($numbers[$i]);
        break;
    }
}

Upvotes: 0

Views: 306

Answers (4)

Toto
Toto

Reputation: 91498

How about:

$arr = range(2,20);
$size = count($arr);
for ($i=0; $i<$size; $i++) {
    for ($j=$size-1; $j>$i; $j--) {
        if ($arr[$j]%$arr[$i]) continue;
        unset($arr[$i]);
        break;
    }
}
print_r($arr);

output:

Array
(
    [9] => 11
    [10] => 12
    [11] => 13
    [12] => 14
    [13] => 15
    [14] => 16
    [15] => 17
    [16] => 18
    [17] => 19
    [18] => 20
)

Upvotes: 0

d4rkpr1nc3
d4rkpr1nc3

Reputation: 1827

Try this:

for($i = 0; $i < count($arr); $i++)
{
    for($j = 0; $j < count($arr); $j++)
    {
        if($arr[$i] != $arr[$j] && $arr[$i] % $arr[$j] === 0)
        {
            unset($arr[$j);
            break;
        }
    }
}

Upvotes: -1

safarov
safarov

Reputation: 7804

For sorted ordered number

$arr = array(2,3,4,5,6,7,8,9,10,11,12,13,14);

$half_c = ceil(count($arr)/2) - 1;
$result_array = array_slice($arr, $half_c);

Edit: For random array you can cut half again, and iterate only first part of array. Prime number theory also can help to write faster algorithm for first part of array.

Upvotes: 1

W. Goeman
W. Goeman

Reputation: 1714

I will not do this in real code, just because I think you want to do that yourself.

LoopA iterating the intput array:
  LoopB iterating the input array:
    check division of loopA value and loopB value, and add the value of loopA to a new array accordingly
  End loopB
End loopA
Print the new array

Note: This is not complete, but it certainly should give you a start on how to continue.

Upvotes: 4

Related Questions