📌  相关文章
📜  查找数组中的所有对 (a, b) 使得 a % b = k

📅  最后修改于: 2021-10-27 08:36:17             🧑  作者: Mango

给定一个具有不同元素的数组,任务是找到数组中满足 a % b = k 的对,其中 k 是给定的整数。

例子 :

Input  :  arr[] = {2, 3, 5, 4, 7}   
              k = 3
Output :  (7, 4), (3, 4), (3, 5), (3, 7)
7 % 4 = 3
3 % 4 = 3
3 % 5 = 3
3 % 7 = 3

一个朴素的解决方案是将所有对一一生成并检查它们的模数是否等于 k。如果等于 k,则打印该对。

C++
// C++ implementation to find such pairs
#include 
using namespace std;
 
// Function to find pair such that (a % b = k)
bool printPairs(int arr[], int n, int k)
{
    bool isPairFound = true;
 
    // Consider each and every pair
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            // Print if their modulo equals to k
            if (i != j && arr[i] % arr[j] == k) {
                cout << "(" << arr[i] << ", "
                     << arr[j] << ")"
                     << " ";
                isPairFound = true;
            }
        }
    }
 
    return isPairFound;
}
 
// Driver program
int main()
{
    int arr[] = { 2, 3, 5, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    if (printPairs(arr, n, k) == false)
        cout << "No such pair exists";
 
    return 0;
}


Java
// Java implementation to find such pairs
 
class Test {
    // method to find pair such that (a % b = k)
    static boolean printPairs(int arr[], int n, int k)
    {
        boolean isPairFound = true;
 
        // Consider each and every pair
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // Print if their modulo equals to k
                if (i != j && arr[i] % arr[j] == k) {
                    System.out.print("(" + arr[i] + ", " + arr[j] + ")"
                                     + " ");
                    isPairFound = true;
                }
            }
        }
 
        return isPairFound;
    }
 
    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 2, 3, 5, 4, 7 };
        int k = 3;
 
        if (printPairs(arr, arr.length, k) == false)
            System.out.println("No such pair exists");
    }
}


Python3
# Python3 implementation to find such pairs
 
# Function to find pair such that (a % b = k)
def printPairs(arr, n, k):
 
    isPairFound = True
 
    # Consider each and every pair
    for i in range(0, n):
     
        for j in range(0, n):
         
            # Print if their modulo equals to k
            if (i != j and arr[i] % arr[j] == k):
             
                print("(", arr[i], ", ", arr[j], ")",
                                 sep = "", end = " ")
                isPairFound = True
             
    return isPairFound
 
# Driver Code
arr = [2, 3, 5, 4, 7]
n = len(arr)
k = 3
if (printPairs(arr, n, k) == False):
    print("No such pair exists")
 
# This article is contributed by Smitha Dinesh Semwal.


C#
// C# implementation to find such pair
using System;
 
public class GFG {
     
    // method to find pair such that (a % b = k)
    static bool printPairs(int[] arr, int n, int k)
    {
        bool isPairFound = true;
 
        // Consider each and every pair
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
            {
                // Print if their modulo equals to k
                if (i != j && arr[i] % arr[j] == k)
                {
                    Console.Write("(" + arr[i] + ", "
                                + arr[j] + ")" + " ");
                    isPairFound = true;
                }
            }
        }
 
        return isPairFound;
    }
 
    // Driver method
    public static void Main()
    {
        int[] arr = { 2, 3, 5, 4, 7 };
        int k = 3;
 
        if (printPairs(arr, arr.Length, k) == false)
            Console.WriteLine("No such pair exists");
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
// C++ program to find all pairs such that
// a % b = k.
#include 
using namespace std;
 
// Utiltity function to find the divisors of
// n and store in vector v[]
vector findDivisors(int n)
{
    vector v;
 
    // Vector is used to store  the divisors
    for (int i = 1; i <= sqrt(n); i++) {
        if (n % i == 0) {
            // If n is a square number, push
            // only one occurrence
            if (n / i == i)
                v.push_back(i);
            else {
                v.push_back(i);
                v.push_back(n / i);
            }
        }
    }
    return v;
}
 
// Function to find pairs such that (a%b = k)
bool printPairs(int arr[], int n, int k)
{
    // Store all the elements in the map
    // to use map as hash for finding elements
    // in O(1) time.
    unordered_map occ;
    for (int i = 0; i < n; i++)
        occ[arr[i]] = true;
 
    bool isPairFound = false;
    for (int i = 0; i < n; i++) {
        // Print all the pairs with (a, b) as
        // (k, numbers greater than k) as
        // k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] && k < arr[i]) {
            cout << "(" << k << ", " << arr[i] << ") ";
            isPairFound = true;
        }
 
        // Now check for the current element as 'a'
        // how many b exists such that a%b = k
        if (arr[i] >= k) {
            // find all the divisors of (arr[i]-k)
            vector v = findDivisors(arr[i] - k);
 
            // Check for each divisor i.e. arr[i] % b = k
            // or not, if yes then print that pair.
            for (int j = 0; j < v.size(); j++) {
                if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) {
                    cout << "(" << arr[i] << ", "
                         << v[j] << ") ";
                    isPairFound = true;
                }
            }
 
            // Clear vector
            v.clear();
        }
    }
 
    return isPairFound;
}
 
// Driver program
int main()
{
    int arr[] = { 3, 1, 2, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
 
    if (printPairs(arr, n, k) == false)
        cout << "No such pair exists";
    return 0;
}


Java
// Java program to find all pairs such that
// a % b = k.
 
import java.util.HashMap;
import java.util.Vector;
 
class Test {
    // Utility method to find the divisors of
    // n and store in vector v[]
    static Vector findDivisors(int n)
    {
        Vector v = new Vector<>();
 
        // Vector is used to store  the divisors
        for (int i = 1; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                // If n is a square number, push
                // only one occurrence
                if (n / i == i)
                    v.add(i);
                else {
                    v.add(i);
                    v.add(n / i);
                }
            }
        }
        return v;
    }
 
    // method to find pairs such that (a%b = k)
    static boolean printPairs(int arr[], int n, int k)
    {
        // Store all the elements in the map
        // to use map as hash for finding elements
        // in O(1) time.
        HashMap occ = new HashMap<>();
        for (int i = 0; i < n; i++)
            occ.put(arr[i], true);
 
        boolean isPairFound = false;
        for (int i = 0; i < n; i++) {
            // Print all the pairs with (a, b) as
            // (k, numbers greater than k) as
            // k % (num (> k)) = k i.e. 2%4 = 2
            if (occ.get(k) && k < arr[i]) {
                System.out.print("(" + k + ", " + arr[i] + ") ");
                isPairFound = true;
            }
 
            // Now check for the current element as 'a'
            // how many b exists such that a%b = k
            if (arr[i] >= k) {
                // find all the divisors of (arr[i]-k)
                Vector v = findDivisors(arr[i] - k);
 
                // Check for each divisor i.e. arr[i] % b = k
                // or not, if yes then print that pair.
                for (int j = 0; j < v.size(); j++) {
                    if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) {
                        System.out.print("(" + arr[i] + ", "
                                         + v.get(j) + ") ");
                        isPairFound = true;
                    }
                }
 
                // Clear vector
                v.clear();
            }
        }
 
        return isPairFound;
    }
 
    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 3, 1, 2, 5, 4 };
        int k = 2;
 
        if (printPairs(arr, arr.length, k) == false)
            System.out.println("No such pair exists");
    }
}


Python3
# Python3 program to find all pairs
# such that a % b = k.
  
# Utiltity function to find the divisors
# of n and store in vector v[]
import math as mt
 
def findDivisors(n):
 
    v = []
 
    # Vector is used to store the divisors
    for i in range(1, mt.floor(n**(.5)) + 1):
        if (n % i == 0):
             
            # If n is a square number, push
            # only one occurrence
            if (n / i == i):
                v.append(i)
            else:
                v.append(i)
                v.append(n // i)
                 
    return v
 
# Function to find pairs such that (a%b = k)
def printPairs(arr, n, k):
 
    # Store all the elements in the map
    # to use map as hash for finding elements
    # in O(1) time.
    occ = dict()
    for i in range(n):
        occ[arr[i]] = True
 
    isPairFound = False
 
    for i in range(n):
         
        # Print all the pairs with (a, b) as
        # (k, numbers greater than k) as
        # k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] and k < arr[i]):
            print("(", k, ",", arr[i], ")", end = " ")
            isPairFound = True
 
        # Now check for the current element as 'a'
        # how many b exists such that a%b = k
        if (arr[i] >= k):
             
            # find all the divisors of (arr[i]-k)
            v = findDivisors(arr[i] - k)
 
            # Check for each divisor i.e. arr[i] % b = k
            # or not, if yes then prthat pair.
            for j in range(len(v)):
                if (arr[i] % v[j] == k and
                    arr[i] != v[j] and
                    occ[v[j]]):
                    print("(", arr[i], ",", v[j],
                                       ")", end = " ")
                    isPairFound = True
 
    return isPairFound
 
# Driver Code
arr = [3, 1, 2, 5, 4]
n = len(arr)
k = 2
 
if (printPairs(arr, n, k) == False):
    print("No such pair exists")
 
# This code is contributed by mohit kumar


C#
// C# program to find all pairs
// such that a % b = k.
using System;
using System.Collections.Generic;
 
class GFG
{
// Utility method to find the divisors
// of n and store in vector v[]
public static List findDivisors(int n)
{
    List v = new List();
 
    // Vector is used to store
    // the divisors
    for (int i = 1;
             i <= Math.Sqrt(n); i++)
    {
        if (n % i == 0)
        {
            // If n is a square number,
            // push only one occurrence
            if (n / i == i)
            {
                v.Add(i);
            }
            else
            {
                v.Add(i);
                v.Add(n / i);
            }
        }
    }
    return v;
}
 
// method to find pairs such
// that (a%b = k)
public static bool printPairs(int[] arr,
                              int n, int k)
{
    // Store all the elements in the
    // map to use map as hash for
    // finding elements in O(1) time.
    Dictionary occ = new Dictionary();
    for (int i = 0; i < n; i++)
    {
        occ[arr[i]] = true;
    }
 
    bool isPairFound = false;
    for (int i = 0; i < n; i++)
    {
        // Print all the pairs with (a, b) as
        // (k, numbers greater than k) as
        // k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] && k < arr[i])
        {
            Console.Write("(" + k + ", " +
                           arr[i] + ") ");
            isPairFound = true;
        }
 
        // Now check for the current element
        // as 'a' how many b exists such that
        // a%b = k
        if (arr[i] >= k)
        {
            // find all the divisors of (arr[i]-k)
            List v = findDivisors(arr[i] - k);
 
            // Check for each divisor i.e.
            // arr[i] % b = k or not, if
            // yes then print that pair.
            for (int j = 0; j < v.Count; j++)
            {
                if (arr[i] % v[j] == k &&
                    arr[i] != v[j] && occ[v[j]])
                {
                    Console.Write("(" + arr[i] +
                                  ", " + v[j] + ") ");
                    isPairFound = true;
                }
            }
 
            // Clear vector
            v.Clear();
        }
    }
 
    return isPairFound;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {3, 1, 2, 5, 4};
    int k = 2;
 
    if (printPairs(arr, arr.Length, k) == false)
    {
        Console.WriteLine("No such pair exists");
    }
}
}
 
// This code is contributed by Shrikant13


Javascript


输出:

(3, 5) (3, 4) (3, 7) (7, 4)

时间复杂度: O(n 2 )
一个有效的解决方案基于以下观察:

  1. 如果 k 本身存在于 arr[] 中,则 k 与所有元素 arr[i] 形成对,其中 k < arr[i]。对于所有这些 arr[i],我们有 k % arr[i] = k。
  2. 对于所有大于或等于 k 的元素,我们使用以下事实。
If arr[i] % arr[j] = k, 
   ==> arr[i] = x * arr[j] + k
   ==> (arr[i] - k) = x * arr[j]
  We find all divisors of (arr[i] - k)
  and see if they are present in arr[].

为了快速检查数组中是否存在元素,我们使用散列。

C++

// C++ program to find all pairs such that
// a % b = k.
#include 
using namespace std;
 
// Utiltity function to find the divisors of
// n and store in vector v[]
vector findDivisors(int n)
{
    vector v;
 
    // Vector is used to store  the divisors
    for (int i = 1; i <= sqrt(n); i++) {
        if (n % i == 0) {
            // If n is a square number, push
            // only one occurrence
            if (n / i == i)
                v.push_back(i);
            else {
                v.push_back(i);
                v.push_back(n / i);
            }
        }
    }
    return v;
}
 
// Function to find pairs such that (a%b = k)
bool printPairs(int arr[], int n, int k)
{
    // Store all the elements in the map
    // to use map as hash for finding elements
    // in O(1) time.
    unordered_map occ;
    for (int i = 0; i < n; i++)
        occ[arr[i]] = true;
 
    bool isPairFound = false;
    for (int i = 0; i < n; i++) {
        // Print all the pairs with (a, b) as
        // (k, numbers greater than k) as
        // k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] && k < arr[i]) {
            cout << "(" << k << ", " << arr[i] << ") ";
            isPairFound = true;
        }
 
        // Now check for the current element as 'a'
        // how many b exists such that a%b = k
        if (arr[i] >= k) {
            // find all the divisors of (arr[i]-k)
            vector v = findDivisors(arr[i] - k);
 
            // Check for each divisor i.e. arr[i] % b = k
            // or not, if yes then print that pair.
            for (int j = 0; j < v.size(); j++) {
                if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) {
                    cout << "(" << arr[i] << ", "
                         << v[j] << ") ";
                    isPairFound = true;
                }
            }
 
            // Clear vector
            v.clear();
        }
    }
 
    return isPairFound;
}
 
// Driver program
int main()
{
    int arr[] = { 3, 1, 2, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
 
    if (printPairs(arr, n, k) == false)
        cout << "No such pair exists";
    return 0;
}

Java

// Java program to find all pairs such that
// a % b = k.
 
import java.util.HashMap;
import java.util.Vector;
 
class Test {
    // Utility method to find the divisors of
    // n and store in vector v[]
    static Vector findDivisors(int n)
    {
        Vector v = new Vector<>();
 
        // Vector is used to store  the divisors
        for (int i = 1; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                // If n is a square number, push
                // only one occurrence
                if (n / i == i)
                    v.add(i);
                else {
                    v.add(i);
                    v.add(n / i);
                }
            }
        }
        return v;
    }
 
    // method to find pairs such that (a%b = k)
    static boolean printPairs(int arr[], int n, int k)
    {
        // Store all the elements in the map
        // to use map as hash for finding elements
        // in O(1) time.
        HashMap occ = new HashMap<>();
        for (int i = 0; i < n; i++)
            occ.put(arr[i], true);
 
        boolean isPairFound = false;
        for (int i = 0; i < n; i++) {
            // Print all the pairs with (a, b) as
            // (k, numbers greater than k) as
            // k % (num (> k)) = k i.e. 2%4 = 2
            if (occ.get(k) && k < arr[i]) {
                System.out.print("(" + k + ", " + arr[i] + ") ");
                isPairFound = true;
            }
 
            // Now check for the current element as 'a'
            // how many b exists such that a%b = k
            if (arr[i] >= k) {
                // find all the divisors of (arr[i]-k)
                Vector v = findDivisors(arr[i] - k);
 
                // Check for each divisor i.e. arr[i] % b = k
                // or not, if yes then print that pair.
                for (int j = 0; j < v.size(); j++) {
                    if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) {
                        System.out.print("(" + arr[i] + ", "
                                         + v.get(j) + ") ");
                        isPairFound = true;
                    }
                }
 
                // Clear vector
                v.clear();
            }
        }
 
        return isPairFound;
    }
 
    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 3, 1, 2, 5, 4 };
        int k = 2;
 
        if (printPairs(arr, arr.length, k) == false)
            System.out.println("No such pair exists");
    }
}

蟒蛇3

# Python3 program to find all pairs
# such that a % b = k.
  
# Utiltity function to find the divisors
# of n and store in vector v[]
import math as mt
 
def findDivisors(n):
 
    v = []
 
    # Vector is used to store the divisors
    for i in range(1, mt.floor(n**(.5)) + 1):
        if (n % i == 0):
             
            # If n is a square number, push
            # only one occurrence
            if (n / i == i):
                v.append(i)
            else:
                v.append(i)
                v.append(n // i)
                 
    return v
 
# Function to find pairs such that (a%b = k)
def printPairs(arr, n, k):
 
    # Store all the elements in the map
    # to use map as hash for finding elements
    # in O(1) time.
    occ = dict()
    for i in range(n):
        occ[arr[i]] = True
 
    isPairFound = False
 
    for i in range(n):
         
        # Print all the pairs with (a, b) as
        # (k, numbers greater than k) as
        # k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] and k < arr[i]):
            print("(", k, ",", arr[i], ")", end = " ")
            isPairFound = True
 
        # Now check for the current element as 'a'
        # how many b exists such that a%b = k
        if (arr[i] >= k):
             
            # find all the divisors of (arr[i]-k)
            v = findDivisors(arr[i] - k)
 
            # Check for each divisor i.e. arr[i] % b = k
            # or not, if yes then prthat pair.
            for j in range(len(v)):
                if (arr[i] % v[j] == k and
                    arr[i] != v[j] and
                    occ[v[j]]):
                    print("(", arr[i], ",", v[j],
                                       ")", end = " ")
                    isPairFound = True
 
    return isPairFound
 
# Driver Code
arr = [3, 1, 2, 5, 4]
n = len(arr)
k = 2
 
if (printPairs(arr, n, k) == False):
    print("No such pair exists")
 
# This code is contributed by mohit kumar

C#

// C# program to find all pairs
// such that a % b = k.
using System;
using System.Collections.Generic;
 
class GFG
{
// Utility method to find the divisors
// of n and store in vector v[]
public static List findDivisors(int n)
{
    List v = new List();
 
    // Vector is used to store
    // the divisors
    for (int i = 1;
             i <= Math.Sqrt(n); i++)
    {
        if (n % i == 0)
        {
            // If n is a square number,
            // push only one occurrence
            if (n / i == i)
            {
                v.Add(i);
            }
            else
            {
                v.Add(i);
                v.Add(n / i);
            }
        }
    }
    return v;
}
 
// method to find pairs such
// that (a%b = k)
public static bool printPairs(int[] arr,
                              int n, int k)
{
    // Store all the elements in the
    // map to use map as hash for
    // finding elements in O(1) time.
    Dictionary occ = new Dictionary();
    for (int i = 0; i < n; i++)
    {
        occ[arr[i]] = true;
    }
 
    bool isPairFound = false;
    for (int i = 0; i < n; i++)
    {
        // Print all the pairs with (a, b) as
        // (k, numbers greater than k) as
        // k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] && k < arr[i])
        {
            Console.Write("(" + k + ", " +
                           arr[i] + ") ");
            isPairFound = true;
        }
 
        // Now check for the current element
        // as 'a' how many b exists such that
        // a%b = k
        if (arr[i] >= k)
        {
            // find all the divisors of (arr[i]-k)
            List v = findDivisors(arr[i] - k);
 
            // Check for each divisor i.e.
            // arr[i] % b = k or not, if
            // yes then print that pair.
            for (int j = 0; j < v.Count; j++)
            {
                if (arr[i] % v[j] == k &&
                    arr[i] != v[j] && occ[v[j]])
                {
                    Console.Write("(" + arr[i] +
                                  ", " + v[j] + ") ");
                    isPairFound = true;
                }
            }
 
            // Clear vector
            v.Clear();
        }
    }
 
    return isPairFound;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {3, 1, 2, 5, 4};
    int k = 2;
 
    if (printPairs(arr, arr.Length, k) == false)
    {
        Console.WriteLine("No such pair exists");
    }
}
}
 
// This code is contributed by Shrikant13

Javascript


输出:

(2, 3) (2, 5) (5, 3) (2, 4)

时间复杂度: O(n* sqrt(max)) 其中 max 是数组中的最大元素。
参考:
https://stackoverflow.com/questions/12732939/find-pairs-in-an-array-such-that-ab-k-where-k-is-a-given-integer

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程