📌  相关文章
📜  打印所有对都可被m整除的k个数字

📅  最后修改于: 2021-05-04 17:15:22             🧑  作者: Mango

给定一个整数数组和两个数字k和m。打印数组中的k个数字,以使任意两对之间的差异可被m整除。如果没有k数字,则打印-1。

例子:

Input: arr[] = {1, 8, 4}
           k = 2 
           m = 3    
Output: 1 4 
Explanation: Difference between
1 and 4 is divisible by 3.

Input: arr[] = {1, 8, 4} 
       k = 3 
       m = 3 
Output: -1 
Explanation: there are only two numbers 
whose difference is divisible by m, but 
k is three here which is not possible, 
hence we print -1.

一个简单的方法是对每个元素进行迭代,并与所有其他元素进行检查,并且如果其差可被m整除的数字计数大于k,则等于k,那么我们将通过再次迭代来打印这k个数字。但这并不能有效,因为它运行两个嵌套循环。
时间复杂度:O(n * n)
辅助空间:O(1)

一种有效的方法是应用数学方法,其中我们知道(xy)%m是否等于x%m – y%m。因此,如果我们可以存储除以m时剩下相同余数的所有数字,
如果剩下相同余数的数字计数大于k或等于k,那么我们得到答案,因为所有剩下相同余数的数字。

下面是上述方法的实现

C++
// CPP program to find a list of k elements from
// an array such that difference between all of
// them is divisible by m.
#include 
using namespace std;
  
// function to generate k numbers whose difference 
// is divisible by m
void print_result(int a[], int n, int k, int m)
{
    // Using an adjacency list like representation
    // to store numbers that lead to same 
    // remainder.
    vector v[m];
  
    for (int i = 0; i < n; i++) {
  
        // stores the modulus when divided
        // by m
        int rem = a[i] % m;
  
        v[rem].push_back(a[i]);
          
        // If we found k elements which
        // have same remainder.
        if (v[rem].size() == k)
        {
            for (int j = 0; j < k; j++) 
                cout << v[rem][j] << " ";
            return;             
        } 
    }
    
    // If we could not find k elements
    cout << "-1";
}
  
// driver program to test the above function
int main()
{
    int a[] = { 1, 8, 4 };
    int n = sizeof(a) / sizeof(a[0]);
    print_result(a, n, 2, 3);
    return 0;
}


Java
// Java program to find a list of k elements from
// an array such that difference between all of
// them is divisible by m.
import java.util.*;
class GFG 
{
  
// function to generate k numbers whose difference 
// is divisible by m
static void print_result(int a[], int n, 
                         int k, int m)
{
    // Using an adjacency list like representation
    // to store numbers that lead to same 
    // remainder.
    Vector> v = new Vector>(m);
    for(int i = 0; i < m; i++) 
        v.add(new Vector());
  
    for (int i = 0; i < n; i++)
    {
  
        // stores the modulus when divided
        // by m
        int rem = a[i] % m;
  
        v.get(rem).add(a[i]);
          
        // If we found k elements which
        // have same remainder.
        if (v.get(rem).size() == k)
        {
            for (int j = 0; j < k; j++) 
                System.out.print(v.get(rem).get(j) + " ");
            return;             
        } 
    }
      
    // If we could not find k elements
    System.out.print("-1");
}
  
// Driver Code
public static void main(String[] args) 
{
    int a[] = { 1, 8, 4 };
    int n = a.length;
    print_result(a, n, 2, 3);
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find a list of k elements from
# an array such that difference between all of
# them is divisible by m.
  
# function to generate k numbers whose difference
# is divisible by m
def print_result(a, n, k, m):
  
    # Using an adjacency list like representation
    # to store numbers that lead to same
    # remainder.
    v = [[] for i in range(m)]
  
    for i in range(0, n):
  
        # stores the modulus when divided
        # by m
        rem = a[i] % m
  
        v[rem].append(a[i])
  
        # If we found k elements which
        # have same remainder.
        if(len(v[rem]) == k):
  
            for j in range(0, k):
                print(v[rem][j], end=" ")
            return
  
    # If we could not find k elements
    print(-1)
  
# driver program to test the above function
if __name__=='__main__':
    a = [1, 8, 4]
    n = len(a)
    print_result(a, n, 2, 3)
  
# This code is contributed by
# Sanjit_Prasad


C#
// C# program to find a list of k elements from
// an array such that difference between all of
// them is divisible by m.
using System;
using System.Collections.Generic;
  
class GFG 
{
  
// function to generate k numbers whose difference 
// is divisible by m
static void print_result(int []a, int n, 
                         int k, int m)
{
    // Using an adjacency list like representation
    // to store numbers that lead to same 
    // remainder.
    List> v = new List>(m);
    for(int i = 0; i < m; i++) 
        v.Add(new List());
  
    for (int i = 0; i < n; i++)
    {
  
        // stores the modulus when divided
        // by m
        int rem = a[i] % m;
  
        v[rem].Add(a[i]);
          
        // If we found k elements which
        // have same remainder.
        if (v[rem].Count == k)
        {
            for (int j = 0; j < k; j++) 
                Console.Write(v[rem][j] + " ");
            return;             
        } 
    }
      
    // If we could not find k elements
    Console.Write("-1");
}
  
// Driver Code
public static void Main(String[] args) 
{
    int []a = { 1, 8, 4 };
    int n = a.Length;
    print_result(a, n, 2, 3);
}
}
  
// This code is contributed by PrinciRaj1992


PHP


输出:

1 4 

时间复杂度: O(n)
辅助空间: O(m)