Search code examples
javaarraysnumberscomparemultiplication

How do I find two values in an array that multiply to a certain number


What I'm trying to do is search through an array and find out if there's two numbers that multiply to 225. Here's what I have right now:

    int n = A.length;

    for(int i = 0; i >= n; i++){
        for(int j = 0; j >= n; j++){
            if(i == j){
            }
            else if(A[i] * A[j] == 225){
                return true;
            }
        }
    }
    return false;
}

What happens is it finds the first value in the array and multiplys that with every other value and once it finds two numbers that are 225 then it returns true. I also made it so that if i and j are the same number then it does nothing because I don't want it comparing values in the same position. The problem is it keeps on returning false even on array's which do have two numbers that multiply to 225 (like 15, 45, 60, 15). So what's wrong with my code.


Solution

  • you have 1 problem with for loop:

    it should look like this:

    int n = A.length;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            if(i != j)
                if(A[i] * A[j] == 225)
                    return true;
    

    also, you could optimize this loop a little bit to:

    int n = A.length;
    for(int i = 0; i < (n-1); i++)
        for(int j = (i+1); j < n; j++)
            if (A[i] * A[j] == 225)
                return true;
    

    here is a little bit different version, which has average complexity O(N):

        final Map<Integer, Boolean> set = new HashMap<>(A.length);
        for (final int i : A) {
            set.put(i, set.containsKey(i)); // store number from array, set to true if there are multiple occurrences of 2 numbers
        }
        for (final int i : A) {
            final int mult = 225 / i;
            if ((mult * i) == 225) { // test that integral multiplication leads to 225
                final Boolean m = set.get(mult);
                if (m != null) { // we have both numbers in set, now we should filter double counting
                    if ((i != mult) || ((i == mult) && m.booleanValue()))
                        return true;
                }
    
            }
        }
        return false;