text: Minimize sum of prime numbers added to make an array non | Pthon3 Program to implement the above approach ; Stores if an index is a prime / non - prime value ; Stores the prime ; Function to generate all prime numbers ; If current element is prime ; Set all its multiples non - prime ; Store all prime numbers ; Function to find the closest prime to a particular number ; Applying binary search on primes vector ; If the prime added makes the elements equal ; Return this as the closest prime ; If the array remains non - decreasing ; Search for a bigger prime number ; Otherwise ; Check if a smaller prime can make array non - decreasing or not ; Return closest number ; Function to find the minimum cost ; Find all primes ; Store the result ; Iterate over the array ; Current element is less than the previous element ; Find the closest prime which makes the array non decreasing ; Add to overall cost ; Update current element ; Return the minimum cost ; Driver Code ; Given array ; Function Call
code: MAX = 10000000 NEW_LINE isPrime = [ True ] * ( MAX + 1 ) NEW_LINE primes = [ ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global isPrime NEW_LINE p = 2 NEW_LINE while p * p <= MAX : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def prime_search ( primes , diff ) : NEW_LINE INDENT low = 0 NEW_LINE high = len ( primes ) - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( primes [ mid ] == diff ) : NEW_LINE INDENT return primes [ mid ] NEW_LINE DEDENT elif ( primes [ mid ] < diff ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT res = primes [ mid ] NEW_LINE high = mid - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def minCost ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT diff = arr [ i - 1 ] - arr [ i ] NEW_LINE closest_prime = prime_search ( primes , diff ) NEW_LINE res += closest_prime NEW_LINE arr [ i ] += closest_prime NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 5 , 4 , 3 ] NEW_LINE n = 5 NEW_LINE print ( minCost ( arr , n ) ) NEW_LINE DEDENT