Larger of a^b or b^a in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds out the larger among the ab and ba

It's a straightforward problem. Let's see the steps to solve it.

  • Initialise the values of a and b.
  • Take the log of both the values.
  • Compute the values of $b\:\log\:a$ and $a\:\log\:b$
  • Compare the both values.
  • If $a\:\log\:b$ is greater than $b\:\log\:a$, then print bais greater.
  • If $b\:\log\:a$ is greater than $a\:\log\:b$, then print abis greater.
  • Else print both are equal.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int a = 4, b = 7;
   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;
   return 0;


If you run the above code, then you will get the following result.

a ^ b is greater


If you have any queries in the tutorial, mention them in the comment section.

Updated on 09-Apr-2021 13:18:53