Number of 0 s and 1 s at prime positions in the given array | C ++ implementation of the approach ; Function that returns true if n is prime ; Check from 2 to n ; Function to find the count of 0 s and 1 s at prime indices ; To store the count of 0 s and 1 s ; If current 0 is at prime position ; If current 1 is at prime position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } void countPrimePosition ( int arr [ ] , int n ) { int c0 = 0 , c1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 && isPrime ( i ) ) c0 ++ ; if ( arr [ i ] == 1 && isPrime ( i ) ) c1 ++ ; } cout << " Number ▁ of ▁ 0s ▁ = ▁ " << c0 << endl ; cout << " Number ▁ of ▁ 1s ▁ = ▁ " << c1 ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPrimePosition ( arr , n ) ; return 0 ; }