Scott
Scott

Reputation: 301

Integer Math Array Optimization?

I'm looking for optimization of this function:

public bool isDivideEvenly (int[] num, int[] div)
{    
    for (int x = 0; x < num.length; x++)
    {    
        for (int y = 0; y < div.length; y++)
        {    
            if (num[x] % div[y] == 0) return true;
        }    
    }    
}

Upvotes: 0

Views: 70

Answers (2)

AShelly
AShelly

Reputation: 35580

in a similar vein to @glowcoder's answer - it may be a win to filter the divisors of div first to remove multiples. For example, no need to keep 9 if you have 3.

The effectiveness of this would be very data dependent. It would work best if div was much smaller than num and had many multiples. It would just add cost if div was all primes.

Upvotes: 1

corsiKa
corsiKa

Reputation: 82589

If you sort div, you could do some searching on it that would allow you to reduce the number of divs. Whether or not this will save you time is dependent on the machine and your data. But, for example, if your smallest number is 1 and your largest number is smaller than the current x value, you don't need to search the array because none of them will work.

Upvotes: 0

Related Questions