This is the second solution to find the pairs of numbers in which their sum is divisible by 9 from an array of integers. This method uses the core logic of traversing array using nested for loops, add any two numbers come across in each iteration, and then uses a simple predicate to verify that the sum is divisible by 9.
import java.util.function.Predicate;
public class Divby9 {
public static void divBy9Pairs(int[] tempArr, Predicate<Integer> div9) {
System.out.println("The hardcoded array of integers given below");
System.out.print("[ ");
for(int i=0;i<tempArr.length;i++)
System.out.print(tempArr[i]+" ");
System.out.println("]");
/*Traverse through the array using nested for loop, and check whether
*the sum of the successive numbers divisible by 9 */
System.out.println("The pairs of numbers which are divisible by 9");
for (int i=0;i<tempArr.length;i++)
for(int j=i+1;j<tempArr.length;j++)
if (div9.test(tempArr[i]+tempArr[j]))
System.out.println(tempArr[i]+" "+tempArr[j]);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] intArr= {14,20,7,16,25,34,4};
System.out.println("OUTPUT:");
//Calling the function divby9 which computes the sum of pairs divisible by 9
divBy9Pairs(intArr, (i)-> i%9==0);
}
}
OUTPUT:
The hardcoded array of integers given below
[ 14 20 7 16 25 34 4 ]
The pairs of numbers which are divisable by 9
14 4
20 7
20 16
20 25
20 34

Leave a comment