📜  在两个指数中找到较大的指数

📅  最后修改于: 2021-05-06 20:00:01             🧑  作者: Mango

给定四个整数ABCD。现在的任务是找出哪个更大的A BC D。

例子:

天真的方法:计算A BC D的值,然后将它们进行比较。当值更大(例如562145 321457)时,此方法将失败。

高效的方法:使用log,我们可以将术语写为log(A B )log(C D ) ,也可以将它们写成B * log(A)D * log(C) 。这些值比原始值更容易计算和比较。

下面是上述方法的实现:

C++
// C++ implementation of the approach
  
#include
using namespace std;
  
// Function to find whether a^b is greater or c^d
void compareValues(int a, int b, int c, int d)
{
  
    // Find b * log(a)
    double log1 = log10(a);
    double num1 = log1 * b;
  
    // Find d * log(c)
    double log2 = log10(c);
    double num2 = log2 * d;
  
    // Compare both values
    if (num1 > num2)
        cout << a  << "^"  <<  b;
    else
        cout << c << "^" << d;
}
  
// Driver code
int main ()
{
    int a = 8, b = 29, c = 60, d = 59;
    compareValues(a, b, c, d);
}
  
  
// This code is contributed by ihritik


Java
// Java implementation of the approach
class GFG {
  
    // Function to find whether a^b is greater or c^d
    static void compareValues(int a, int b, int c, int d)
    {
  
        // Find b * log(a)
        double log1 = Math.log10(a);
        double num1 = log1 * b;
  
        // Find d * log(c)
        double log2 = Math.log10(c);
        double num2 = log2 * d;
  
        // Compare both values
        if (num1 > num2)
            System.out.println(a + "^" + b);
        else
            System.out.println(c + "^" + d);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int a = 8, b = 29, c = 60, d = 59;
        compareValues(a, b, c, d);
    }
}


Python3
# Python3 implementation of the approach
import math
  
# Function to find whether 
# a^b is greater or c^d
def compareValues(a, b, c, d): 
# Find b * log(a)
    log1 = math.log10(a)
    num1 = log1 * b
  
    # Find d * log(c)
    log2 = math.log10(c)
    num2 = log2 * d
  
    # Compare both values
    if num1 > num2 :
        print(a, '^', b)
    else :
        print(c, '^', d)
  
# Driver code
a = 8
b = 29
c = 60
d = 59
  
# Function call
compareValues(a, b, c, d)
  
# This code is contributed by nidhiva


C#
// C# implementation of the approach
using System;
  
class GFG 
{
  
    // Function to find whether
    // a^b is greater or c^d
    static void compareValues(int a, int b, 
                              int c, int d)
    {
  
        // Find b * log(a)
        double log1 = Math.Log10(a);
        double num1 = log1 * b;
  
        // Find d * log(c)
        double log2 = Math.Log10(c);
        double num2 = log2 * d;
  
        // Compare both values
        if (num1 > num2)
            Console.WriteLine(a + "^" + b);
        else
            Console.WriteLine(c + "^" + d);
    }
  
    // Driver code
    public static void Main ()
    {
        int a = 8, b = 29, c = 60, d = 59;
        compareValues(a, b, c, d);
    }
}
  
// This code is contributed by ihritik


输出:
60^59