Find the larger exponential among two exponentials
Last Updated :
19 Dec, 2022
Given four integers A, B, C and D. The task is to find which is greater AB or CD.
Examples:
Input: A = 2, B = 5, C = 4, D = 2
Output: 2^5
25 = 32
42 = 16
Input: A = 8, B = 29, C = 60, D = 59
Output: 60^59
Naive approach: Calculate the values of AB and CD then compare them. This approach will fail when the values are greater say 562145321457.
Efficient approach: Using the log, we can write the terms log(AB) and log(CD) which can also be written as B * log(A) and D * log(C). These values are easier to calculate and compare than the original values.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void compareValues( int a, int b, int c, int d)
{
double log1 = log10 (a);
double num1 = log1 * b;
double log2 = log10 (c);
double num2 = log2 * d;
if (num1 > num2)
cout << a << "^" << b;
else
cout << c << "^" << d;
}
int main ()
{
int a = 8, b = 29, c = 60, d = 59;
compareValues(a, b, c, d);
}
|
Java
import java.io.*;
class GFG {
static void compareValues( int a, int b, int c, int d)
{
double log1 = Math.log10(a);
double num1 = log1 * b;
double log2 = Math.log10(c);
double num2 = log2 * d;
if (num1 > num2)
System.out.println(a + "^" + b);
else
System.out.println(c + "^" + d);
}
public static void main(String[] args)
{
int a = 8 , b = 29 , c = 60 , d = 59 ;
compareValues(a, b, c, d);
}
}
|
Python3
import math
def compareValues(a, b, c, d):
log1 = math.log10(a)
num1 = log1 * b
log2 = math.log10(c)
num2 = log2 * d
if num1 > num2 :
print (a, '^' , b)
else :
print (c, '^' , d)
a = 8
b = 29
c = 60
d = 59
compareValues(a, b, c, d)
|
C#
using System;
class GFG
{
static void compareValues( int a, int b,
int c, int d)
{
double log1 = Math.Log10(a);
double num1 = log1 * b;
double log2 = Math.Log10(c);
double num2 = log2 * d;
if (num1 > num2)
Console.WriteLine(a + "^" + b);
else
Console.WriteLine(c + "^" + d);
}
public static void Main ()
{
int a = 8, b = 29, c = 60, d = 59;
compareValues(a, b, c, d);
}
}
|
Javascript
<script>
function compareValues(a, b, c, d)
{
let log1 = Math.log(a) / Math.log(10);
let num1 = log1 * b;
let log2 = Math.log(c) / Math.log(10);
let num2 = log2 * d;
if (num1 > num2)
document.write(a + "^" + b);
else
document.write(c + "^" + d);
}
let a = 8, b = 29, c = 60, d = 59;
compareValues(a, b, c, d);
</script>
|
Time complexity: O(1)
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...