给定两个数字 ,发现哪个更大 。
如果 ,则打印a ^ b更大
如果 ,打印b ^ a更大
如果 ,打印两者相等
例子:
Input : 3 5
Output : a^b is greater
3^5 = 243, 5^3 = 125. Since, 243>125, therefore a^b > b^a.
Input : 2 4
Output : Both are equal
2^4 = 16, 4^2 = 16. Since, 16=16, therefore a^b = b^a.
蛮力解决方案将是只计算并比较它们。但是由于可以足够大即使int long int也无法存储,所以此解决方案不可行。同样计算幂n至少需要时间使用快速求幂技术。
有效的方法是使用对数。我们必须比较 。如果我们取日志,问题就会减少到比较 。
因此,
如果 ,则打印a ^ b更大
如果 ,打印b ^ a更大
如果 ,打印两者相等
下面是上面讨论的有效方法的实现。
C++
// C++ code for finding greater
// between the a^b and b^a
#include
using namespace std;
// Function to find the greater value
void findGreater(int a, int b)
{
long double x = (long double)a * (long double)(log((long double)(b)));
long double y = (long double)b * (long double)(log((long double)(a)));
if (y > x) {
cout << "a^b is greater" << endl;
}
else if (y < x) {
cout << "b^a is greater" << endl;
}
else {
cout << "Both are equal" << endl;
}
}
// Driver code
int main()
{
int a = 3, b = 5, c = 2, d = 4;
findGreater(a, b);
findGreater(c, d);
return 0;
}
Java
// Java code for finding greater
// between the a^b and b^a
public class GFG{
// Function to find the greater value
static void findGreater(int a, int b)
{
double x = (double)a * (double)(Math.log((double)(b)));
double y = (double)b * (double)(Math.log((double)(a)));
if (y > x) {
System.out.println("a^b is greater") ;
}
else if (y < x) {
System.out.println("b^a is greater") ;
}
else {
System.out.println("Both are equal") ;
}
}
// Driver code
public static void main(String []args)
{
int a = 3, b = 5, c = 2, d = 4;
findGreater(a, b);
findGreater(c, d);
}
// This code is contributed by Ryuga
}
Python 3
# Python 3 code for finding greater
# between the a^b and b^a
import math
# Function to find the greater value
def findGreater(a, b):
x = a * (math.log(b));
y = b * (math.log(a));
if (y > x):
print ("a^b is greater");
elif (y < x):
print("b^a is greater");
else :
print("Both are equal");
# Driver code
a = 3;
b = 5;
c = 2;
d = 4;
findGreater(a, b);
findGreater(c, d);
# This code is contributed
# by Shivi_Aggarwal
C#
// C# code for finding greater
// between the a^b and b^a
using System;
public class GFG{
// Function to find the greater value
static void findGreater(int a, int b)
{
double x = (double)a * (double)(Math.Log((double)(b)));
double y = (double)b * (double)(Math.Log((double)(a)));
if (y > x) {
Console.Write("a^b is greater\n") ;
}
else if (y < x) {
Console.Write("b^a is greater"+"\n") ;
}
else {
Console.Write("Both are equal") ;
}
}
// Driver code
public static void Main()
{
int a = 3, b = 5, c = 2, d = 4;
findGreater(a, b);
findGreater(c, d);
}
}
PHP
$x)
{
echo "a^b is greater", "\n";
}
else if ($y < $x)
{
echo "b^a is greater", "\n" ;
}
else
{
echo "Both are equal", "\n" ;
}
}
// Driver code
$a = 3;
$b = 5;
$c = 2;
$d = 4;
findGreater($a, $b);
findGreater($c, $d);
// This code is contributed by ajit
?>
Javascript
输出:
a^b is greater
Both are equal
时间复杂度: O(1)
辅助空间: O(1)