📌  相关文章
📜  用于配对的Java程序,其中一个是另一个的幂倍数

📅  最后修改于: 2022-05-13 01:54:45.466000             🧑  作者: Mango

用于配对的Java程序,其中一个是另一个的幂倍数

给定一个包含 n 个元素的数组 A[] 和一个正整数 k。现在您已经找到了 Ai、Aj 对的数量,使得Ai = Aj*(k x )其中 x 是一个整数。
注意: (Ai, Aj) 和 (Aj, Ai) 必须计算一次。
例子 :

Input : A[] = {3, 6, 4, 2},  k = 2
Output : 2
Explanation : We have only two pairs 
(4, 2) and (3, 6)

Input : A[] = {2, 2, 2},   k = 2
Output : 3
Explanation : (2, 2), (2, 2), (2, 2) 
that are (A1, A2), (A2, A3) and (A1, A3) are 
total three pairs where Ai = Aj * (k^0) 

为了解决这个问题,我们首先对给定的数组进行排序,然后对于每个元素 Ai,对于不同的 x 值,我们找到等于值 Ai * k^x 的元素数,直到 Ai * k^x 小于或等于最大哎。
算法:

// sort the given array
    sort(A, A+n);

    // for each A[i] traverse rest array
    for (int i=0; i
 
 

Java










// Java program to find pairs count 
import java.io.*; 
import java .util.*; 
  
class GFG { 
      
    // function to count the required pairs 
    static int countPairs(int A[], int n, int k)  
    { 
        int ans = 0; 
          
        // sort the given array 
        Arrays.sort(A); 
          
        // for each A[i] traverse rest array 
        for (int i = 0; i < n; i++) { 
            for (int j = i + 1; j < n; j++)  
            { 
          
                // count Aj such that Ai*k^x = Aj 
                int x = 0; 
              
                // increase x till Ai * k^x <= largest element 
                while ((A[i] * Math.pow(k, x)) <= A[j])  
                { 
                    if ((A[i] * Math.pow(k, x)) == A[j])  
                    { 
                        ans++; 
                        break; 
                    } 
                    x++; 
                } 
            } 
        } 
        return ans; 
    } 
      
    // Driver program 
    public static void main (String[] args)  
    { 
        int A[] = {3, 8, 9, 12, 18, 4, 24, 2, 6}; 
        int n = A.length; 
        int k = 3; 
        System.out.println (countPairs(A, n, k)); 
          
    } 
} 
  
// This code is contributed by vt_m. 







Output : 6 Please refer complete article on Pairs such that one is a power multiple of other for more details!