Program to compare m^n and n^m
Last Updated :
20 Dec, 2022
Given two positive integers m and n, the task is to write a program that checks whether m^n is greater than, less than, or equal to n^m.
Examples :
Input: m = 3, n = 10
Output: m^n > n^m
Explanation : 3^10=59049 which is greater than 10^3=1000
Input: m = 987654321, n = 123456987
Output: m^n < n^m
A naive approach is to compute m^n and n^m, which causes overflow when m and n are very large.
An efficient approach is to solve this problem using log.
Given LHS = m^n and RHS = n^m.
After taking log on both sides, LHS = n*log(m) and RHS = m*log(n)
Then compare the LHS and RHS.
C++
#include <bits/stdc++.h>
using namespace std;
void check(unsigned long long m, unsigned long long int n)
{
double RHS = m * ( double ) log (n);
double LHS = n * ( double ) log (m);
if ( LHS > RHS )
cout << "m^n > n^m" ;
else if ( LHS < RHS )
cout << "m^n < n^m" ;
else
cout << "m^n = n^m" ;
}
int main() {
unsigned long long m = 987654321, n = 123456987;
check(m, n);
return 0;
}
|
Java
import java .io.*;
class GFG
{
static void check( long m, long n)
{
double RHS = m * ( double )Math.log(n);
double LHS = n * ( double )Math.log(m);
if (LHS > RHS)
System.out.print( "m^n > n^m" );
else if (LHS < RHS)
System.out.print( "m^n < n^m" );
else
System.out.print( "m^n = n^m" );
}
static public void main (String[] args)
{
long m = 987654321 , n = 123456987 ;
check(m, n);
}
}
|
Python3
import math
def check( m, n):
RHS = m * math.log(n);
LHS = n * math.log(m);
if (LHS > RHS):
print ( "m^n > n^m" );
elif (LHS < RHS):
print ( "m^n < n^m" );
else :
print ( "m^n = n^m" );
m = 987654321 ;
n = 123456987 ;
check(m, n);
|
C#
using System;
class GFG
{
static void check( ulong m, ulong n)
{
double RHS = m * ( double )Math.Log(n);
double LHS = n * ( double )Math.Log(m);
if (LHS > RHS)
Console.Write( "m^n > n^m" );
else if (LHS < RHS)
Console.Write( "m^n < n^m" );
else
Console.Write( "m^n = n^m" );
}
static public void Main ()
{
ulong m = 987654321, n = 123456987;
check(m, n);
}
}
|
PHP
<?php
function check( $m , $n )
{
$RHS = $m * log( $n );
$LHS = $n * log( $m );
if ( $LHS > $RHS )
echo "m^n > n^m" ;
else if ( $LHS < $RHS )
echo "m^n < n^m" ;
else
echo "m^n = n^m" ;
}
$m = 987654321;
$n = 123456987;
check( $m , $n );
?>
|
Javascript
<script>
function check( m, n)
{
var RHS = m * Math.log(n);
var LHS = n * Math.log(m);
if (LHS > RHS){
document.write( "m^n > n^m" );
}
else if (LHS < RHS) {
document.write( "m^n < n^m" );
}
else {
document.write( "m^n = n^m" );
}
}
var m = 987654321 ;
var n = 123456987;
check(m, n);
</script>
|
Time Complexity: O(max(log(m), log(n)))
Auxiliary Space: O(max(log(m), log(n))), due to the recursion call stack.
Share your thoughts in the comments
Please Login to comment...