Given two integer X and Y, the task is compare XY and YX for large values of X and Y.
Examples:
Input: X = 2, Y = 3
Output: 2^3 < 3^2
23 < 32
Input: X = 4, Y = 5
Output: 4^5 > 5^4
Naive approach: A basic approach is to find the values XY and YX and compare them which can overflow as the values of X and Y can be large
Better approach: Taking log of both the equations, log(XY) = Y * log(X) and log(YX) = X * log(Y). Now, these values can be compared easily without overflows.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void compareVal( int x, int y)
{
long double a = y * log (x);
long double b = x * log (y);
if (a > b)
cout << x << "^" << y << " > "
<< y << "^" << x;
else if (a < b)
cout << x << "^" << y << " < "
<< y << "^" << x;
else if (a == b)
cout << x << "^" << y << " = "
<< y << "^" << x;
}
int main()
{
long double x = 4, y = 5;
compareVal(x, y);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void compareVal( int x, int y)
{
double a = y * Math.log(x);
double b = x * Math.log(y);
if (a > b)
System.out.print(x + "^" + y + " > " +
y + "^" + x);
else if (a < b)
System.out.print(x + "^" + y + " < " +
y + "^" + x);
else if (a == b)
System.out.print(x + "^" + y + " = " +
y + "^" + x );
}
public static void main(String[] args)
{
int x = 4 , y = 5 ;
compareVal(x, y);
}
}
|
Python3
from math import log
def compareVal(x, y) :
a = y * log(x);
b = x * log(y);
if (a > b) :
print (x, "^" , y, ">" , y, "^" , x);
elif (a < b) :
print (x, "^" , y, "<" , y , "^" , x);
elif (a = = b) :
print (x, "^" , y, "=" , y, "^" , x);
if __name__ = = "__main__" :
x = 4 ; y = 5 ;
compareVal(x, y);
|
C#
using System;
class GFG
{
static void compareVal( double x, double y)
{
double a = y * Math.Log(x);
double b = x * Math.Log(y);
if (a > b)
Console.Write (x + "^" + y + " > " +
y + "^" + x);
else if (a < b)
Console.Write (x + "^" + y + " < " +
y + "^" + x);
else if (a == b)
Console.Write (x + "^" + y + " = " +
y + "^" + x );
}
static public void Main ()
{
double x = 4, y = 5;
compareVal(x, y);
}
}
|
Javascript
<script>
function compareVal(x, y)
{
let a = y * Math.log(x);
let b = x * Math.log(y);
if (a > b)
document.write(x + "^" + y + " > "
+ y + "^" + x);
else if (a < b)
document.write(x + "^" + y + " < "
+ y + "^" + x);
else if (a == b)
document.write(x + "^" + y + " = "
+ y + "^" + x);
}
let x = 4, y = 5;
compareVal(x, y);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!