Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix
Examples:
Input : m = 3, n = 3 { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } Output : Frequency of odd number = 5 Frequency of even number = 4 Input : m = 3, n = 3 { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } Output : Frequency of odd number = 4 Frequency of even number = 5
Javascript
<script> // Java Script Program to Find the frequency // of even and odd numbers in a matrix let MAX = 100; // function for calculating frequency function freq(ar,m,n) { let even = 0, odd = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers document.write( " Frequency of odd number =" + odd + " <br>" ); document.write( " Frequency of even number = " + even + "<br>" ); } // Driver code let m = 3, n = 3; let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; freq(array, m, n); // This code is contributed by sravan kumar G </script> |
Output:
Frequency of odd number = 5 Frequency of even number = 4
Time Complexity: O(m*n)
Auxiliary Space: O(1)
Method: Using bitwise & operator
Javascript
<script> // Java Script Program to Find the frequency // of even and odd numbers in a matrix let MAX = 100; // function for calculating frequency function freq(ar,m,n) { let even = 0, odd = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { // even and odd //checking using bitwise & operator if ((ar[i][j]&1) == 0) ++even; else ++odd; } } // print Frequency of numbers document.write( " Frequency of odd number =" + odd + " <br>" ); document.write( " Frequency of even number = " + even + "<br>" ); } // Driver code let m = 3, n = 3; let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; freq(array, m, n); // This code is contributed by tvsk </script> |
Output:
Frequency of odd number = 5 Frequency of even number = 4
Time Complexity: O(m*n)
Auxiliary Space: O(1)
Please refer complete article on Frequencies of even and odd numbers in a matrix for more details!