Dada una array A[] y un número x, verifique el par en A[] con la suma como x (también conocida como Two Sum) – Part 1

Escriba un programa que, dado un arreglo A[] de n números y otro número x, determine si existen o no dos elementos en A[] cuya suma sea exactamente x. 

Ejemplos: 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find and print pair
bool chkPair(int A[], int size, int x) {
  for (int i = 0; i < (size - 1); i++) {
    for (int j = (i + 1); j < size; j++) {
      if (A[i] + A[j] == x) {
        cout << "Pair with a given sum " << x << +
        " is (" << A[i] << ", " << A[j] << ")" <<
          endl;
 
        return 1;
      }
    }
  }
 
  return 0;
}
 
int main() {
  int A[] = {
    0,
    -1,
    2,
    -3,
    1
  };
  int x = -2;
  int size = sizeof(A) / sizeof(A[0]);
 
  if (chkPair(A, size, x)) {
    cout << "Valid pair exists" << endl;
  } else {
    cout << "No valid pair exists for " << x << endl;
  }
 
  return 0;
}
 
// This code is contributed by Samim Hossain Mondal.

C

/*
  * This C program tells if there exists a pair in array whose sum results in x.
  */
 
#include <stdio.h>
 
// Function to find and print pair
int chkPair(int A[], int size, int x) {
    for (int i = 0; i < (size - 1); i++) {
        for (int j = (i + 1); j < size; j++) {
            if (A[i] + A[j] == x) {
                printf("Pair with a given sum %d is (%d, %d)\n", x, A[i], A[j]);
 
                return 1;
            }
        }
    }
 
    return 0;
}
 
int main(void) {
    int A[] = {0, -1, 2, -3, 1};
    int x = -2;
    int size = sizeof(A) / sizeof(A[0]);
 
    if (chkPair(A, size, x)) {
        printf("Valid pair exists\n");
    }
    else {
        printf("No valid pair exists for %d\n", x);
    }
 
    return 0;
}
// This code is contributed by Manish Kumar (mkumar2789)

Java

// Java program to check if there exists a pair
// in array whose sum results in x.
class GFG{
 
  // Function to find and print pair
  static boolean chkPair(int A[], int size, int x) {
      for (int i = 0; i < (size - 1); i++) {
          for (int j = (i + 1); j < size; j++) {
              if (A[i] + A[j] == x) {
                  System.out.println("Pair with a given sum " + x +
                                     " is (" + A[i] + ", " + A[j] + ")");
   
                  return true;
              }
          }
      }
 
      return false;
  }
 
  public static void main(String [] args) {
     
      int A[] = {0, -1, 2, -3, 1};
      int x = -2;
      int size = A.length;
 
      if (chkPair(A, size, x)) {
          System.out.println("Valid pair exists");
      }
      else {
          System.out.println("No valid pair exists for " + x );
      }
  }
}
 
// This code is contributed by umadevi9616

Python3

# This python program tells if there exists a pair in array whose sum results in x.
 
# Function to find and print pair
def chkPair(A, size, x):
    for i in range(0, size - 1):
        for j in range(i + 1, size):
            if (A[i] + A[j] == x):
                print(f"Pair with a given sum {x} is ({A[i]},{A[j]})")
 
                return 1
    return 0
 
if __name__ == "__main__":
    A = [0, -1, 2, -3, 1]
    x = -2
    size = len(A)
 
    if (chkPair(A, size, x)):
        print("Valid pair exists")
 
    else:
        print(f"No valid pair exists for {x}")
 
    # This code is contributed by rakeshsahni

C#

// C# program to check if there exists a pair
// in array whose sum results in x.
using System;
class GFG{
 
  // Function to find and print pair
  static bool chkPair(int [] A, int size, int x) {
      for (int i = 0; i < (size - 1); i++) {
          for (int j = (i + 1); j < size; j++) {
              if (A[i] + A[j] == x) {
                  Console.WriteLine("Pair with a given sum " + x +
                                     " is (" + A[i] + ", " + A[j] + ")");
   
 
                  return true;
              }
          }
      }
 
      return false;
  }
 
  public static void Main()
  {
      int [] A = {0, -1, 2, -3, 1};
      int x = -2;
      int size = A.Length;
 
      if (chkPair(A, size, x)) {
          Console.WriteLine("Valid pair exists");
      }
      else {
          Console.WriteLine("No valid pair exists for " + x );
      } 
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript

<script>
 
// Javascript program to check if there exists a pair
// in array whose sum results in x.
 
// Function to find and print pair
    function chkPair(A , size , x) {
     
        for (i = 0; i < (size - 1); i++) {
            for (j = (i + 1); j < size; j++) {
      
                if (A[i] + A[j] == x) {
                    document.write("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")");
 
                    return true;
                }
            }
        }
 
        return false;
    }
 
        let A = [ 0, -1, 2, -3, 1 ];
        let x = -2;
        let size = A.length;
 
        if (chkPair(A, size, x)) {
            document.write("<br/>Valid pair exists");
        }
        else {
            document.write("<br/>No valid pair exists for " + x);
        }
 
 
// This code is contributed by Samim Hossain Mondal.
</script>

Go

package main
import ("fmt")
 
 
func twoSum(nums [5]int, target int) {
    var flag bool = false
    result:=make([]int,2)
    for i:=0;i<len(nums)-1;i++{
        for j:=i+1;j<len(nums);j++{
            if nums[i]+nums[j]==target{
                result[0]=nums[i]
                result[1]=nums[j]
                flag = true;
            }
        }
    }
     
    if(flag == false){
        fmt.Println("No valid pair exists for " , target)
    }else {
      fmt.Printf( "Pair with a given sum " , target , " is (" , result[0], ", " , result[1] , ")")
   }
     
}
 
func main() {
   
  arr2 := [5]int{0, -1, 2, -3, 1}
  var x int = -2
 
  twoSum(arr2, x)
}
// This code is contributed by NITUGAUR

C++

// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(int A[], int arr_size,
                           int sum)
{
    int l, r;
 
    /* Sort the elements */
    sort(A, A + arr_size);
 
    /* Now look for the two candidates in
       the sorted array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[i] + A[j] > sum
            r--;
    }
    return 0;
}
 
/* Driver program to test above function */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, -8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    // Function calling
    if (hasArrayTwoCandidates(A, arr_size, n))
        cout << "Array has two elements"
                " with given sum";
    else
        cout << "Array doesn't have two"
                " elements with given sum";
 
    return 0;
}

C

// C program to check if given array
// has 2 elements whose sum is equal
// to the given value
 
#include <stdio.h>
#define bool int
 
void quickSort(int*, int, int);
 
bool hasArrayTwoCandidates(
    int A[], int arr_size, int sum)
{
    int l, r;
 
    /* Sort the elements */
    quickSort(A, 0, arr_size - 1);
 
    /* Now look for the two candidates in the sorted
       array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[i] + A[j] > sum
            r--;
    }
    return 0;
}
 
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
    PURPOSE */
void exchange(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
 
int partition(int A[], int si, int ei)
{
    int x = A[ei];
    int i = (si - 1);
    int j;
 
    for (j = si; j <= ei - 1; j++) {
        if (A[j] <= x) {
            i++;
            exchange(&A[i], &A[j]);
        }
    }
    exchange(&A[i + 1], &A[ei]);
    return (i + 1);
}
 
/* Implementation of Quick Sort
A[] --> Array to be sorted
si  --> Starting index
ei  --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
    int pi; /* Partitioning index */
    if (si < ei) {
        pi = partition(A, si, ei);
        quickSort(A, si, pi - 1);
        quickSort(A, pi + 1, ei);
    }
}
 
/* Driver program to test above function */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, -8 };
    int n = 16;
    int arr_size = 6;
 
    if (hasArrayTwoCandidates(A, arr_size, n))
        printf("Array has two elements with given sum");
    else
        printf("Array doesn't have two elements with given sum");
 
    getchar();
    return 0;
}

Java

// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;
 
class GFG {
    // Function to check if array has 2 elements
    // whose sum is equal to the given value
    static boolean hasArrayTwoCandidates(
        int A[],
        int arr_size, int sum)
    {
        int l, r;
 
        /* Sort the elements */
        Arrays.sort(A);
 
        /* Now look for the two candidates
        in the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return true;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return false;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = A.length;
 
        // Function calling
        if (hasArrayTwoCandidates(A, arr_size, n))
            System.out.println("Array has two "
                               + "elements with given sum");
        else
            System.out.println("Array doesn't have "
                               + "two elements with given sum");
    }
}

Python

# Python program to check for the sum
# condition to be satisfied
 
def hasArrayTwoCandidates(A, arr_size, sum):
     
    # sort the array
    quickSort(A, 0, arr_size-1)
    l = 0
    r = arr_size-1
     
    # traverse the array for the two elements
    while l<r:
        if (A[l] + A[r] == sum):
            return 1
        elif (A[l] + A[r] < sum):
            l += 1
        else:
            r -= 1
    return 0
 
# Implementation of Quick Sort
# A[] --> Array to be sorted
# si  --> Starting index
# ei  --> Ending index
def quickSort(A, si, ei):
    if si < ei:
        pi = partition(A, si, ei)
        quickSort(A, si, pi-1)
        quickSort(A, pi + 1, ei)
 
# Utility function for partitioning
# the array(used in quick sort)
def partition(A, si, ei):
    x = A[ei]
    i = (si-1)
    for j in range(si, ei):
        if A[j] <= x:
            i += 1
             
            # This operation is used to swap
            # two variables is python
            A[i], A[j] = A[j], A[i]
 
        A[i + 1], A[ei] = A[ei], A[i + 1]
         
    return i + 1
     
 
# Driver program to test the functions
A = [1, 4, 45, 6, 10, -8]
n = 16
if (hasArrayTwoCandidates(A, len(A), n)):
    print("Array has two elements with the given sum")
else:
    print("Array doesn't have two elements
                                  with the given sum")
 
## This code is contributed by __Devesh Agrawal__

C#

// C# program to check for pair
// in A[] with sum as x
 
using System;
 
class GFG {
    static bool hasArrayTwoCandidates(int[] A,
                       int arr_size, int sum)
    {
        int l, r;
 
        /* Sort the elements */
        sort(A, 0, arr_size - 1);
 
        /* Now look for the two candidates
        in the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return true;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return false;
    }
 
    /* Below functions are only to sort the
    array using QuickSort */
 
    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    static int partition(int[] arr, int low, int high)
    {
        int pivot = arr[high];
 
        // index of smaller element
        int i = (low - 1);
        for (int j = low; j <= high - 1; j++) {
            // If current element is smaller
            // than or equal to pivot
            if (arr[j] <= pivot) {
                i++;
 
                // swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
 
        // swap arr[i+1] and arr[high] (or pivot)
        int temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;
 
        return i + 1;
    }
 
    /* The main function that
    implements QuickSort()
    arr[] --> Array to be sorted,
    low --> Starting index,
    high --> Ending index */
    static void sort(int[] arr, int low, int high)
    {
        if (low < high) {
            /* pi is partitioning index, arr[pi]
            is now at right place */
            int pi = partition(arr, low, high);
 
            // Recursively sort elements before
            // partition and after partition
            sort(arr, low, pi - 1);
            sort(arr, pi + 1, high);
        }
    }
 
    // Driver code
    public static void Main()
    {
        int[] A = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = 6;
 
        if (hasArrayTwoCandidates(A, arr_size, n))
            Console.Write("Array has two elements"
                          + " with given sum");
        else
            Console.Write("Array doesn't have "
                          + "two elements with given sum");
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// PHP program to check if given
// array has 2 elements whose sum
// is equal to the given value
 
// Function to check if array has
// 2 elements whose sum is equal
// to the given value
function hasArrayTwoCandidates($A, $arr_size,
                                        $sum)
{
    $l; $r;
 
    /* Sort the elements */
    //sort($A, A + arr_size);
    sort($A);
 
    /* Now look for the two candidates
    in the sorted array*/
    $l = 0;
    $r = $arr_size - 1;
    while ($l < $r)
    {
        if($A[$l] + $A[$r] == $sum)
            return 1;
        else if($A[$l] + $A[$r] < $sum)
            $l++;
        else // A[i] + A[j] > sum
            $r--;
    }
    return 0;
}
 
// Driver Code
$A = array (1, 4, 45, 6, 10, -8);
$n = 16;
$arr_size = sizeof($A);
 
// Function calling
if(hasArrayTwoCandidates($A, $arr_size, $n))
    echo "Array has two elements " .
                   "with given sum";
else
    echo "Array doesn't have two " .
          "elements with given sum";
     
// This code is contributed by m_kit
?>

Javascript

<script>
 
// Javascript program to check if given array
// has 2 elements whose sum is equal
// to the given value
 
// Function to check if array has 2 elements
// whose sum is equal to the given value
function hasArrayTwoCandidates(A, arr_size, sum)
{
    var l, r;
 
    /* Sort the elements */
    A.sort();
 
    /* Now look for the two candidates in
    the sorted array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[i] + A[j] > sum
            r--;
    }
    return 0;
}
 
/* Driver program to test above function */
var A = [ 1, 4, 45, 6, 10, -8 ]
var n = 16;
var arr_size = A.length;
// Function calling
if (hasArrayTwoCandidates(A, arr_size, n))
    document.write("Array has two elements" +
            " with the given sum");
else
    document.write("Array doesn't have two" +
            " elements with the given sum");
 
</script>

C++

// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include <bits/stdc++.h>
 
using namespace std;
 
void printPairs(int arr[], int arr_size, int sum)
{
    unordered_set<int> s;
    for (int i = 0; i < arr_size; i++)
    {
        int temp = sum - arr[i];
 
        if (s.find(temp) != s.end())
            cout << "Pair with given sum "
                 << sum << " is (" << arr[i] << ","
                    << temp << ")" << endl;
 
        s.insert(arr[i]);
    }
}
 
/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    // Function calling
    printPairs(A, arr_size, n);
 
    return 0;
}

C

// C program to check if given array
// has 2 elements whose sum is equal
// to the given value
 
#include <stdio.h>
#define MAX 100000
 
// NOTE: Works only if range elements is limited
// target - arr[i] >= 0 && target - arr[i] < MAX
 
 
 
void printPairs(int arr[], int arr_size, int target)
{
    int i, temp;
 
    /*initialize hash set as 0*/
    int s[MAX] = { 0 };
 
    for (i = 0; i < arr_size; i++)
    {
        temp = target - arr[i];
        if (s[temp] == 1)
            printf(
                "Pair with given sum %d is (%d, %d) \n",
                target, arr[i], temp);
        s[arr[i]] = 1;
    }
}
 
/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int target = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    printPairs(A, arr_size, target);
 
    getchar();
    return 0;
}

Java

// Java implementation using Hashing
import java.io.*;
import java.util.HashSet;
 
class PairSum {
    static void printpairs(int arr[], int sum)
    {
        HashSet<Integer> s = new HashSet<Integer>();
        for (int i = 0; i < arr.length; ++i)
        {
            int temp = sum - arr[i];
 
            // checking for condition
            if (s.contains(temp)) {
                System.out.println(
                    "Pair with given sum "
                    + sum + " is (" + arr[i]
                    + ", " + temp + ")");
            }
            s.add(arr[i]);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        printpairs(A, n);
    }
}
 
// This article is contributed by Aakash Hasija

Python3

# Python program to find if there are
# two elements with given sum
 
# function to check for the given sum
# in the array
def printPairs(arr, arr_size, sum):
     
    # Create an empty hash map
    # using an hashmap allows us to store the indices
    hashmap = {}
     
    for i in range(0, arr_size):
        temp = sum-arr[i]
        if (temp in hashmap):
            print (f'Pair with given sum {sum} is ({temp},{arr[i]}) at indices ({hashmap[temp]},{i})')
        hashmap[arr[i]] = i
 
# driver code
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n)
 
# This code will also work in case the array has the same number twice
# and target is the sum of those numbers
# Eg: Array = [4,6,4] Target = 8
 
# This code is contributed by __Achyut Upadhyay__

C#

// C# implementation using Hashing
using System;
using System.Collections.Generic;
 
class GFG {
    static void printpairs(int[] arr,
                           int sum)
    {
        HashSet<int> s = new HashSet<int>();
        for (int i = 0; i < arr.Length; ++i)
        {
            int temp = sum - arr[i];
 
            // checking for condition
            if (s.Contains(temp)) {
                Console.Write("Pair with given sum " +
           sum + " is (" + arr[i] + ", " + temp + ")");
            }
            s.Add(arr[i]);
        }
    }
 
    // Driver Code
    static void Main()
    {
        int[] A = new int[] { 1, 4, 45,
                              6, 10, 8 };
        int n = 16;
        printpairs(A, n);
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

Javascript

<script>
 
 
// JavaScript program to check if given array
// has 2 elements whose sum is equal
// to the given value
 
// Javascript implementation using Hashing
 
    function printpairs(arr, sum)
    {
        let s = new Set();
        for (let i = 0; i < arr.length; ++i)
        {
            let temp = sum - arr[i];
 
            // checking for condition
            if (s.has(temp)) {
                document.write(
                    "Pair with given sum "
                    + sum + " is (" + arr[i]
                    + ", " + temp + ")");
            }
            s.add(arr[i]);
        }
    }
 
// Driver Code
 
        let A = [ 1, 4, 45, 6, 10, 8 ];
        let n = 16;
        printpairs(A, n);
 
</script>

C++

// Code in cpp to tell if there exists a pair in array whose
// sum results in x.
#include <iostream>
using namespace std;
 
// Function to print pairs
void printPairs(int a[], int n, int x)
{
    int i;
    int rem[x];
    // initializing the rem values with 0's.
    for (i = 0; i < x; i++)
        rem[i] = 0;
    // Perform the remainder operation only if the element
    // is x, as numbers greater than x can't be used to get
    // a sum x. Updating the count of remainders.
    for (i = 0; i < n; i++)
        if (a[i] < x)
            rem[a[i] % x]++;
 
    // Traversing the remainder list from start to middle to
    // find pairs
    for (i = 1; i < x / 2; i++) {
        if (rem[i] > 0 && rem[x - i] > 0) {
            // The elements with remainders i and x-i will
            // result to a sum of x. Once we get two
            // elements which add up to x , we print x and
            // break.
            cout << "Yes\n";
            break;
        }
    }
 
    // Once we reach middle of remainder array, we have to
    // do operations based on x.
    if (i >= x / 2) {
        if (x % 2 == 0) {
            // if x is even and we have more than 1 elements
            // with remainder x/2, then we will have two
            // distinct elements which add up to x. if we
            // dont have more than 1 element, print "No".
            if (rem[x / 2] > 1)
                cout << "Yes\n";
            else
                cout << "No\n";
        }
        else {
            // When x is odd we continue the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                cout << "Yes\n";
            else
                cout << "No\n";
        }
    }
}
 
/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    // Function calling
    printPairs(A, arr_size, n);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// Code in c to tell if there exists a pair in array whose
// sum results in x.
#include <stdio.h>
 
// Function to print pairs
void printPairs(int a[], int n, int x)
{
    int i;
    int rem[x];
    // initializing the rem values with 0's.
    for (i = 0; i < x; i++)
        rem[i] = 0;
    // Perform the remainder operation only if the element
    // is x, as numbers greater than x can't be used to get
    // a sum x. Updating the count of remainders.
    for (i = 0; i < n; i++)
        if (a[i] < x)
            rem[a[i] % x]++;
 
    // Traversing the remainder list from start to middle to
    // find pairs
    for (i = 1; i < x / 2; i++) {
        if (rem[i] > 0 && rem[x - i] > 0) {
            // The elements with remainders i and x-i will
            // result to a sum of x. Once we get two
            // elements which add up to x , we print x and
            // break.
            printf("Yes\n");
            break;
        }
    }
 
    // Once we reach middle of remainder array, we have to
    // do operations based on x.
    if (i >= x / 2) {
        if (x % 2 == 0) {
            // if x is even and we have more than 1 elements
            // with remainder x/2, then we will have two
            // distinct elements which add up to x. if we
            // dont have more than 1 element, print "No".
            if (rem[x / 2] > 1)
                printf("Yes\n");
            else
                printf("No\n");
        }
        else {
            // When x is odd we continue the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
}
 
/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    // Function calling
    printPairs(A, arr_size, n);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Code in Java to tell if there exists a pair in array
// whose sum results in x.
import java.util.*;
 
class GFG {
 
    // Function to print pairs
    static void printPairs(int a[], int n, int x)
    {
        int i;
        int[] rem = new int[x];
        // initializing the rem values with 0's.
        for (i = 0; i < x; i++)
            rem[i] = 0;
        // Perform the remainder operation only if
        // the element is x, as numbers greater than
        // x can't be used to get a sum x. Updating
        // the count of remainders.
        for (i = 0; i < n; i++)
            if (a[i] < x)
                rem[a[i] % x]++;
 
        // Traversing the remainder list from start to
        // middle to find pairs
        for (i = 1; i < x / 2; i++) {
            if (rem[i] > 0 && rem[x - i] > 0) {
                // The elements with remainders i and x-i
                // will result to a sum of x. Once we get
                // two elements which add up to x , we print
                // x and break.
                System.out.println("Yes");
                break;
            }
        }
 
        // Once we reach middle of remainder array, we have
        // to do operations based on x.
        if (i >= x / 2) {
            if (x % 2 == 0) {
                // if x is even and we have more than 1
                // elements with remainder x/2, then we
                // will have two distinct elements which
                // add up to x. if we dont have more
                // than 1 element, print "No".
                if (rem[x / 2] > 1)
                    System.out.println("Yes");
                else
                    System.out.println("No");
            }
            else {
 
                // When x is odd we continue the same
                // process which we did in previous loop.
                if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                    System.out.println("Yes");
                else
                    System.out.println("No");
            }
        }
    }
 
    /* Driver Code */
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.length;
 
        // Function calling
        printPairs(A, arr_size, n);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Python3

# Code in Python3 to tell if there
# exists a pair in array whose
# sum results in x.
 
# Function to print pairs
def printPairs(a, n, x):
     
    rem = []
     
    for i in range(x):
 
        # Initializing the rem
        # values with 0's.
        rem.append(0)
 
    for i in range(n):
        if (a[i] < x):
 
            # Perform the remainder operation
            # only if the element is x, as
            # numbers greater than x can't
            # be used to get a sum x.Updating
            # the count of remainders.
            rem[a[i] % x] += 1
 
    # Traversing the remainder list from
    # start to middle to find pairs
    for i in range(1, x // 2):
        if (rem[i] > 0 and rem[x - i] > 0):
 
            # The elements with remainders
            # i and x-i will result to a
            # sum of x. Once we get two
            # elements which add up to x,
            # we print x and break.
            print("Yes")
            break
 
    # Once we reach middle of
    # remainder array, we have to
    # do operations based on x.
    if (i >= x // 2):
        if (x % 2 == 0):
            if (rem[x // 2] > 1):
 
                # If x is even and we have more
                # than 1 elements with remainder
                # x/2, then we will have two
                # distinct elements which add up
                # to x. if we dont have than 1
                # element, print "No".
                print("Yes")
            else:
                print("No")
        else:
 
            # When x is odd we continue
            # the same process which we
            # did in previous loop.
            if (rem[x // 2] > 0 and
                rem[x - x // 2] > 0):
                print("Yes")
            else:
                print("No")
 
# Driver Code
A = [ 1, 4, 45, 6, 10, 8 ]
n = 16
arr_size = len(A)
 
# Function calling
printPairs(A, arr_size, n)
 
# This code is contributed by subhammahato348

C#

// C# Code in C# to tell if there
// exists a pair in array whose
// sum results in x.
using System;
class GFG
{
   
// Function to print pairs
static void printPairs(int []a, int n, int x)
{
  int i;
  int []rem = new int[x];
  for (i = 0; i < x; i++)
  {
     
    // initializing the rem
    // values with 0's.
    rem[i] = 0;
  }
  for (i = 0; i < n; i++)
  {
    if (a[i] < x)
    {
 
      // Perform the remainder
      // operation only if the
      // element is x, as numbers
      // greater than x can't
      // be used to get a sum x.
      // Updating the count of remainders.
      rem[a[i] % x]++;
    }
  }
 
  // Traversing the remainder list
  // from start to middle to
  // find pairs
  for (i = 1; i < x / 2; i++)
  {
    if (rem[i] > 0 && rem[x - i] > 0)
    {
 
      // The elements with remainders
      // i and x-i will
      // result to a sum of x.
      // Once we get two
      // elements which add up to x ,
      // we print x and
      // break.
      Console.Write("Yes" + "\n");
      break;
    }
  }
 
  // Once we reach middle of
  // remainder array, we have to
  // do operations based on x.
  if (i >= x / 2)
  {
    if (x % 2 == 0)
    {
      if (rem[x / 2] > 1)
      {
 
        // if x is even and
        // we have more than 1
        // elements with remainder
        // x/2, then we will
        // have two distinct elements
        // which add up
        // to x. if we dont have
        //more than 1
        // element, print "No".
        Console.Write("Yes" + "\n");
      }
      else
      {
        Console.Write("No"
                         + "\n");
      }
    }
    else
    {
 
      // When x is odd we continue
      // the same process
      // which we did in previous loop.
      if (rem[x / 2] > 0 &&
          rem[x - x / 2] > 0)
      {
        Console.Write("Yes"
                         + "\n");
      }
      else
      {
        Console.WriteLine("No"
                         + "\n");
      }
    }
  }
}
 
/* Driver Code */
public static void Main(string[] args)
{
    int[] A = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = A.Length;
 
    // Function calling
    printPairs(A, arr_size, n);
}
}
 
// This code is contributed by SoumikMondal

Javascript

<script>
 
// Code in Javascript to tell if there
// exists a pair in array whose
// sum results in x.
 
// Function to print pairs
function printPairs(a, n, x)
{
    let i;
    let rem = new Array(x);
    for(i = 0; i < x; i++)
    {
     
        // Initializing the rem
        // values with 0's.
        rem[i] = 0;
    }
    for(i = 0; i < n; i++)
    {
        if (a[i] < x)
        {
         
            // Perform the remainder
            // operation only if the
            // element is x, as numbers
            // greater than x can't
            // be used to get a sum x.
            // Updating the count of remainders.
            rem[a[i] % x]++;
        }
    }
     
    // Traversing the remainder list
    // from start to middle to
    // find pairs
    for(i = 1; i < x / 2; i++)
    {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
             
            // The elements with remainders
            // i and x-i will
            // result to a sum of x.
            // Once we get two
            // elements which add up to x ,
            // we print x and
            // break.
            document.write("Yes" + "</br>");
            break;
        }
    }
     
    // Once we reach middle of
    // remainder array, we have to
    // do operations based on x.
    if (i >= x / 2)
    {
        if (x % 2 == 0)
        {
            if (rem[x / 2] > 1)
            {
             
                // If x is even and
                // we have more than 1
                // elements with remainder
                // x/2, then we will
                // have two distinct elements
                // which add up
                // to x. if we dont have
                //more than 1
                // element, print "No".
                document.write("Yes" + "</br>");
            }
            else
            {
                document.write("No" + "</br>");
            }
        }
        else
        {
         
            // When x is odd we continue
            // the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 &&
                rem[x - x / 2] > 0)
            {
                document.write("Yes" + "</br>");
            }
            else
            {
                document.write("No" + "</br>");
            }
        }
    }
}
   
// Driver code   
let A = [ 1, 4, 45, 6, 10, 8 ];
let n = 16;
let arr_size = A.length;
 
// Function calling
printPairs(A, arr_size, n);
 
// This code is contributed by suresh07
 
</script>

C++14

#include <bits/stdc++.h>
using namespace std;
 
pair<int,int> findSum(int *arr,int& n,int& target)
{
    int i,findElement;
    unordered_map<int,int>mp;
    pair<int,int>result;
    for(i=0;i<n;i++)
    {
        findElement=target-arr[i];
        if(mp.find(findElement) != mp.end())
        {
            result.first=mp[findElement];
            result.second=i;
          break;
        }
        else mp.insert({arr[i],i});
    }
    return result;
}
 
int main()
{
    int arr[]={1,5,4,3,7,9,2};
    int n=sizeof(arr)/sizeof(arr[0]);
    int search=7;
    pair<int,int>ans=findSum(arr,n,search);
    cout<<min(ans.first,ans.second)<<" "<<max(ans.first,ans.second);
    return 0;
}

Java

// Java Code for above Approach to tell if there exists a pair in array
// whose sum results in x.
import java.io.*;
import java.util.*; 
 
class GFG
{
 
  public static int[] findSum(int arr[], int n, int target)
  {
    int i, findElement;
    Map<Integer,Integer> mp=new HashMap<Integer,Integer>();   
    int result[] = {0,0};
    for(i = 0; i < n; i++)
    {
      findElement = target-arr[i];
      if(mp.containsKey(findElement))
      {
        result[0] = mp.get(findElement);
        result[1] = i;
        break;
      }
      else mp.put(arr[i],i);
    }
    return result;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int A[] = {1,5,4,3,7,9,2};
    int n = A.length;
    int search = 7;
    int ans[] = findSum(A,n,search);
    System.out.println(Math.min(ans[0], ans[1]) + " " +Math.max(ans[0], ans[1]));
  }
}
 
// This code is contributed by kothavvsaakash

Python3

def findSum(arr, n, target):
 
    mp = {}
    result = [0]*2
    for i in range(n):
 
        findElement = target-arr[i]
        if(findElement in mp):
            result[0] = mp[findElement]
            result[1] = i
            break
 
        else:
            mp[arr[i]] = i
    return result
 
# driver code
arr = [1,5,4,3,7,9,2]
n = len(arr)
search = 7
ans = findSum(arr,n,search)
print(f"{min(ans[0], ans[1])} {max(ans[0], ans[1])}")
 
# This code is contributed by shinjanpatra

C#

// C# Code for above Approach to tell if there exists a pair
// in array whose sum results in x.
 
using System;
using System.Collections.Generic;
 
public class GFG {
  // function to find the pair whose sum is target
  public static int[] findSum(int[] arr, int n,
                              int target)
  {
    int i, findElement;
 
    // creating a dictionary
    IDictionary<int, int> mp
      = new Dictionary<int, int>();
 
    // the default result pair
    int[] result = { 0, 0 };
 
    // building the dictionary
    for (i = 0; i < n; i++) {
      findElement = target - arr[i];
      if (mp.ContainsKey(findElement)) {
        result[0] = mp[findElement];
        result[1] = i;
        break;
      }
      else
        mp[arr[i]] = i;
    }
    return result;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    {
      int[] A = { 1, 5, 4, 3, 7, 9, 2 };
      int n = A.Length;
      int search = 7;
 
      // Function call
      int[] ans = findSum(A, n, search);
      Console.WriteLine(Math.Min(ans[0], ans[1]) + " "
                        + Math.Max(ans[0], ans[1]));
    }
  }
}
 
 
//this code is contributed by phasing17

Javascript

<script>
function findSum(arr,n,target)
{
    let i,findElement;
    let mp = new Map();
    let result = [];
    for(i = 0; i < n; i++)
    {
        findElement = target-arr[i];
        if(mp.has(findElement))
        {
            result[0] = mp.get(findElement);
            result[1] = i;
            break;
        }
        else mp.set(arr[i],i);
    }
    return result;
}
 
// driver code
 
let arr = [1,5,4,3,7,9,2];
let n = arr.length;
let search = 7;
let ans = findSum(arr,n,search);
document.write(Math.min(ans[0], ans[1]) + " " +
Math.max(ans[0], ans[1]));
 
// This code is contributed by shinjanpatra
 
</script>

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *