zoukankan      html  css  js  c++  java
  • geeksforgeeks@ Equal to product (Binary Search)

    http://www.practice.geeksforgeeks.org/problem-page.php?pid=667

    Equal to product

    Given an array of integers check whether there are two numbers present with given product.

    Input:

    The first line of input contains an integer T denoting the number of test cases.
    The first line of each test case is N and a product p.
    The second line of each test case contain N number of a[].

    Output:
    Print Yes if two numbers product is equal to p else No.

    Constraints:

    1 ≤ T ≤ 51
    1 ≤ N ≤ 100
    0 ≤ a[] ≤ 1000
    1 ≤ pro ≤ 2000000

    Example:

    Input:

    2

    5 2

    1 2 3 4 5

    8 46

    5 7 9 22 15 344 92 8

    Output:

    Yes

    No

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class GFG {
        
        public static boolean check(int[] arr, int q) {
            
            Arrays.sort(arr);
            int n = arr.length;
            
            for(int i=0; i<n; ++i) {
                if(arr[i] == 0) {
                    if(q == 0) return true;
                    else continue;
                }
                int remain = q % arr[i];
                if(remain != 0) continue;
                
                int div = q / arr[i];
                int pos = Arrays.binarySearch(arr, div);
                if(pos >= 0) {
                    return true;
                }
            }
            return false;
        }
        
        public static void main (String[] args) {
            Scanner in = new Scanner(System.in);
            int times = in.nextInt();
            
            while(times > 0) {
                int n = in.nextInt();
                int q = in.nextInt();
                int[] arr = new int[n];
                
                for(int i=0; i<n; ++i) {
                    arr[i] = in.nextInt();
                }
                
                boolean rs = check(arr, q);
                System.out.println(rs? "Yes": "No");
                --times;
            }
        }
    }
    View Code
  • 相关阅读:
    16解释器模式Interpreter
    15适配器模式Adapter
    14桥接模式Bridge
    13组合模式Composite
    12外观模式Facade
    11代理模式Proxy
    10享元模式Flyweight
    09观察者模式ObServer
    08策略模式Strategy
    07装饰模式Decorator
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5640025.html
Copyright © 2011-2022 走看看