Sum of Maximum and Minimum prime factor of every number in the Array | Javascript implementation of the approach ; max_prime [ i ] represent maximum prime number that divides the number i ; min_prime [ i ] represent minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum prime factor in two arrays ; Check for prime number if min_prime [ i ] > 0 , then it is not a prime number ; if i is a prime number min_prime number that divide prime number and max_prime number that divide prime number is the number itself . ; If this number is being visited for first time then this divisor must be the smallest prime number that divides this number ; The last prime number that divides this number will be maximum . ; Function to find the sum of the minimum and the maximum prime factors of every number from the given array ; Pre - calculation ; For every element of the given array ; The sum of its smallest and largest prime factor ; Driver code
var MAX = 100000 ; var max_prime = Array . from ( { length : MAX + 1 } , ( _ , i ) => 0 ) ; var min_prime = Array . from ( { length : MAX + 1 } , ( _ , i ) => 0 ) ; function sieve ( n ) { for ( var i = 2 ; i <= n ; ++ i ) { if ( min_prime [ i ] > 0 ) { continue ; } min_prime [ i ] = i ; max_prime [ i ] = i ; var j = i + i ; while ( j <= n ) { if ( min_prime [ j ] == 0 ) { min_prime [ j ] = i ; } max_prime [ j ] = i ; j += i ; } } } function findSum ( arr , n ) { sieve ( MAX ) ; for ( i = 0 ; i < n ; i ++ ) { var sum = min_prime [ arr [ i ] ] + max_prime [ arr [ i ] ] ; document . write ( sum + " " ) ; } } var arr = [ 5 , 10 , 15 , 20 , 25 , 30 ] ; var n = arr . length ; findSum ( arr , n ) ;