Sum of array elements which are prime factors of a given number | Function to check if a number is prime or not ; Corner cases ; Check if n is a multiple of 2 or 3 ; Above condition allows to check only for every 6 th number , starting from 5 ; If n is a multiple of i and i + 2 ; Function to find the sum of array elements which are prime factors of K ; Stores the required sum ; Traverse the given array ; If current element is a prime factor of k , add it to the sum ; Print the result ; Given arr [ ] ; Store the size of the array
function isPrime ( n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; var i ; for ( i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } function primeFactorSum ( arr , n , k ) { var sum = 0 ; var i ; for ( i = 0 ; i < n ; i ++ ) { if ( k % arr [ i ] == 0 && isPrime ( arr [ i ] ) ) { sum = sum + arr [ i ] ; } } document . write ( sum ) ; } var arr = [ 1 , 2 , 3 , 5 , 6 , 7 , 15 ] var N = arr . length ; var K = 35 ; primeFactorSum ( arr , N , K ) ;