Count smaller primes on the right of each array element | C ++ Program for the above approach ; Function to check if a number is prime or not ; Function to find the count of smaller primes on the right of each array element ; Stores the count of smaller primes ; If A [ j ] <= A [ i ] and A [ j ] is prime ; Increase count ; Print the count for the current element ; Driver Code ; Function call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; bool is_prime ( int n ) { if ( n <= 1 ) return 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return 0 ; } return 1 ; } void countSmallerPrimes ( int ar [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( ar [ j ] <= ar [ i ] && is_prime ( ar [ j ] ) ) { count ++ ; } } cout << count << " ▁ " ; } } int main ( ) { int ar [ ] = { 43 , 3 , 5 , 7 , 2 , 41 } ; int N = sizeof ar / sizeof ar [ 0 ] ; countSmallerPrimes ( ar , N ) ; return 0 ; }