Sum of all mersenne numbers present in an array | Java implementation of the approach ; Function that returns true if n is a Mersenne number ; Function to return the sum of all the Mersenne numbers from the given array ; To store the required sum ; If current element is a Mersenne number ; Driver code
class GFG { static boolean isMersenne ( int n ) { while ( n != 0 ) { int r = n % 2 ; if ( r == 0 ) return false ; n /= 2 ; } return true ; } static int sumOfMersenne ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 && isMersenne ( arr [ i ] ) ) { sum += arr [ i ] ; } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 17 , 6 , 7 , 63 , 3 } ; int n = arr . length ; System . out . print ( sumOfMersenne ( arr , n ) ) ; } }