How to find pair of numbers to get magic sum

 

Given an array of integers, and a number 'magic', print all the pairs in the array whose sum is equal to 'magic'. If we don't find any pair to get that 'magic' number then just print -1.
Lets see simple java code to get those pair of integer to get that magic number

How to find pair of numbers to get magic sum


Example:


array[] = {3, 1, 4, 8, 9, -1, 5, -4, 0}
magic = 4
OUTPUT: (3, 1), (4, 0), (8, -4), (-1, 5)


public class MagicSum {

 public static void main(String[] args) {
  
  int array[] = new int[] { 3, 1, 4, 8, 9, -1, 5, -4, 0};
  int magic = 4;
  
  new MagicSum().printAllPairs(array, magic);
 }
 
 public void printAllPairs(int[] array, int magic) {
  for (int i =0;i<array.length;i++) {
   
   for (int j=i+1;j<array.length;j++) {
    
    if((array[i]+array[j]) == magic) {
     System.out.println("("+array[i]+", "+array[j]+"), ");
    }
   }
  }
 }
}


OUTPUT:


(3, 1), 
(4, 0), 
(8, -4), 
(-1, 5), 


No comments:
Write comments