Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,941 questions

51,879 answers

573 users

How to count the total pairs whose products exist in an array with Java

2 Answers

0 votes
class Program {
    static int countPairsWhoseProductsExistInArray(int arr[]) {
        int total = 0, size = arr.length;
        
        for (int i = 0; i < size; i++) {
            for (int j = i + 1 ; j < size; j++) {
                int product = arr[i] * arr[j];
 
                for (int k = 0; k < size; k++) {
                    if (arr[k] == product) {
                        total++;
                        break;
                    }
                }
            }
        }
 
        return total;
    }
    public static void main(String[] args) {
        int arr[] = {2, 8, 5, 16, 6, 3, 7, 30} ;
        
        // 2 * 8 = 16
        // 2 * 3 = 6
        // 5 * 6 = 30
        
        System.out.println("Total = " + countPairsWhoseProductsExistInArray(arr));
    }
}
 
 
 
/*
run:
 
Total = 3
 
*/

 



answered Jun 15, 2024 by avibootz
0 votes
import java.util.HashSet;

class Program {
    static int countPairsWhoseProductsExistInArray(int arr[]) {
        int total = 0, size = arr.length;

        HashSet< Integer> Hash = new HashSet<>();
 
        for (int i = 0; i < size; i++) {
            Hash.add(arr[i]);
        }

        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                int product = arr[i] * arr[j];
 
                if (Hash.contains(product)) {
                    total++;
                }
            }
        }

        return total;
    }
    public static void main(String[] args) {
        int arr[] = {2, 8, 5, 16, 6, 3, 7, 30} ;
        
        // 2 * 8 = 16
        // 2 * 3 = 6
        // 5 * 6 = 30
        
        System.out.println("Total = " + countPairsWhoseProductsExistInArray(arr));
    }
}
 
 
 
/*
run:
 
Total = 3
 
*/

 



answered Jun 15, 2024 by avibootz
...