Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,943 questions

51,883 answers

573 users

How to count the odd and even sum of pairs in an array with Java

1 Answer

0 votes
public class Program {
    static void count_odd_and_even_sum_of_pairs(int[] arr, int[] evenodd) {
        int total_even = 0, total_odd = 0;
        int size = arr.length;
     
        for (int i = 0; i < size; i++) {
            if (arr[i] % 2 == 0) {
                total_even++;
            }
            else {
                total_odd++;
            }
        }

        // For all the even elements -> sum of the pair will be even
        int evenPairs = ((total_even * (total_even - 1)) / 2);
     
        // For all the odd elements -> sum of the pair will be even
        evenPairs += ((total_odd * (total_odd - 1)) / 2);
     
        // All even elements * all odd element -> sum of the pair will be odd
        int oddPairs = total_even * total_odd;

        evenodd[0] = evenPairs;
        evenodd[1] = oddPairs;
    }
    public static void main(String[] args) {
        int arr[] = { 1, 2, 3, 4, 5 };
        int[] evenodd = new int[2];
        
        // 1 + 3, 1 + 5, 2 + 4, 3 + 5 = 4 Even
        // 1 + 2, 1 + 4, 2 + 3, 2 + 5, 3 + 4, 4 + 5 = 6 Odd
 
        count_odd_and_even_sum_of_pairs(arr, evenodd);
 
        System.out.println("Total Even Sum = " + evenodd[0] );
        System.out.println("Total Odd Sum = " + evenodd[1]);
    }
}

   
/*
run:
   
Total Even Sum = 4
Total Odd Sum = 6
   
*/

 



answered Jun 16, 2024 by avibootz
edited Jun 16, 2024 by avibootz

Related questions

...