N-th root of a number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the n-th root of a number.

You are given the N-th root and the result of it. You need to find the number such that numberN = result.

Let's see the steps to solve the problem.

  • Initialise the number N and result.
  • Initialise a iterative variable to 1.
  • For every number check whether the result is equal to its n-th power or not.
  • Return the number if the above condition satifies.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getNthRoot(int result, int n) {
   int i = 1;
   while (true) {
      if (pow(i, n) == result) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int result = 64, N = 6;
   cout << getNthRoot(result, N) << endl;
   return 0;
}

Output

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

2

Conclusion

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

raja
Published on 29-Jun-2021 09:21:40
Advertisements