Wednesday, March 17, 2021

How to find pair of two numbers that's multiply equals to Key

  

    import java.util.ArrayList;

    public class FindPair {

        public static void main(String[] args) {
            int arr[] = {1,2,4,6,3,5}; 
            int key = 20; 
            findPair(arr,key);


        }

        private static void findPair(int[] arr, int key) {
            ArrayList<Integer> numbers = new ArrayList<>();
            boolean status = false;
            for(int num : arr) {

                int anotherNumber = (key/num);
                if(numbers.contains(anotherNumber) && (anotherNumber*num) == key) {
                    status=true;
                    System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
                }
                numbers.add(num);
            }
            if(!status)
                System.out.print("No such pair"); 

        }

    }

Output:-

Pair Found:- (4,5)

No comments:

Post a Comment

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....