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


what i'm trying search through array , find out if there's 2 numbers multiply 225. here's have right now:

    int n = a.length;      for(int = 0; >= 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 finds first value in array , multiplys every other value , once finds 2 numbers 225 returns true. made if , j same number nothing because don't want comparing values in same position. problem keeps on returning false on array's have 2 numbers multiply 225 (like 15, 45, 60, 15). what's wrong code.

you have 1 problem loop:

it should this:

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

also, optimize loop little bit to:

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

here little bit different version, has average complexity o(n):

    final map<integer, boolean> set = new hashmap<>(a.length);     (final int : a) {         set.put(i, set.containskey(i)); // store number array, set true if there multiple occurrences of 2 numbers     }     (final int : a) {         final int mult = 225 / i;         if ((mult * i) == 225) { // test integral multiplication leads 225             final boolean m = set.get(mult);             if (m != null) { // have both numbers in set, should filter double counting                 if ((i != mult) || ((i == mult) && m.booleanvalue()))                     return true;             }          }     }     return false; 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -