Minimum element whose n-th power is greater than product of an array of size n
Last Updated :
20 Jul, 2022
Given an array of n integers. Find minimum x which is to be assigned to every array element such that product of all elements of this new array is strictly greater than product of all elements of the initial array.
Examples:
Input: 4 2 1 10 6
Output: 4
Explanation: Product of elements of initial
array 4*2*1*10*6 = 480. If x = 4 then 4*4*
4*4*4 = 480, if x = 3 then 3*3*3*3*3=243.
So minimal element = 4
Input: 3 2 1 4
Output: 3
Explanation: Product of elements of initial
array 3*2*1*4 = 24. If x = 3 then 3*3*3*3
= 81, if x = 2 then 2*2*2*2 = 243. So minimal
element = 3.
Simple Approach: A simple approach is to run a loop from 1 till we find the product is greater than the initial array product.
Time Complexity : O(x^n) and if used pow function then O(x * log n)
Mathematical Approach:
Let, x^n = a1 * a2 * a3 * a4 *....* an
we have been given n and value of a1, a2, a3, ..., an.
Now take log on both sides with base e
n*logex > loge(a1) + loge(a2) +......+ loge(an)
Lets sum = loge(a1) + loge(a2) + ...... + loge(an)
n*loge x > sum
loge x > sum/n
Then take antilog on both side
x > e^(sum/n)
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findMin( int a[], int n)
{
double sum = 0;
for ( int i = 0; i < n; i++)
sum += log (a[i]);
int x = exp (sum / n);
return x + 1;
}
int main()
{
int a[] = { 3, 2, 1, 4 };
int n = sizeof (a) / sizeof (a[0]);
cout << findMin(a, n);
}
|
Java
import java.util.*;
class GFG {
static int findMin( int a[], int n)
{
double sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += Math.log(a[i]);
int x = ( int )Math.exp(sum / n);
return x + 1 ;
}
public static void main(String[] args)
{
int a[] = { 3 , 2 , 1 , 4 };
int n = a.length;
System.out.println(findMin(a, n));
}
}
|
Python3
import math as m
def findMin( a, n):
_sum = 0
for i in range (n):
_sum + = m.log(a[i])
x = m.exp(_sum / n)
return int (x + 1 )
a = [ 3 , 2 , 1 , 4 ]
n = len (a)
print (findMin(a, n))
|
C#
using System;
class GFG {
static int findMin( int []a, int n)
{
double sum = 0;
for ( int i = 0; i < n; i++)
sum += Math.Log(a[i]);
int x = ( int )Math.Exp(sum / n);
return x + 1;
}
public static void Main()
{
int []a = { 3, 2, 1, 4 };
int n = a.Length;
Console.WriteLine(findMin(a, n));
}
}
|
PHP
<?php
function findMin( $a , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += log( $a [ $i ]);
$x = exp ( $sum / $n );
return (int)( $x + 1);
}
$a = array ( 3, 2, 1, 4 );
$n = sizeof( $a );
echo (findMin( $a , $n ));
?>
|
Javascript
<script>
function findMin(a, n)
{
var sum = 0;
for (i = 0; i < n; i++)
sum += Math.log(a[i]);
var x = parseInt( Math.exp(sum / n));
return x + 1;
}
var a = [ 3, 2, 1, 4 ];
var n = a.length;
document.write(findMin(a, n));
</script>
|
Time Complexity: O(n * log(logn))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...