Absolute difference between the Product of Non | Function to find the difference between the product of non - primes and the product of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the product of primes in P1 and the product of non primes in P2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Driver Code ; Find the absolute difference
< ? php function calculateDifference ( $ arr , $ n ) { $ max_val = max ( $ arr ) ; $ prime = array_fill ( 0 , $ max_val , true ) ; $ prime [ 0 ] = false ; $ prime [ 1 ] = false ; for ( $ p = 2 ; $ p * $ p <= $ max_val ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ max_val ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ P1 = 1 ; $ P2 = 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ prime [ $ arr [ $ i ] ] ) { $ P1 *= $ arr [ $ i ] ; } else if ( $ arr [ $ i ] != 1 ) { $ P2 *= $ arr [ $ i ] ; } } return abs ( $ P2 - $ P1 ) ; } $ arr = array ( 1 , 3 , 5 , 10 , 15 , 7 ) ; $ n = count ( $ arr , COUNT_NORMAL ) ; echo CalculateDifference ( $ arr , $ n ) ; ? >