Given two integers N and K, the task is to find the Nth root of the K.
Examples:
Input: N = 3, K = 8
Output: 2.00
Explanation:
Cube root of 8 is 2. i.e. 23 = 8
Input: N = 2, K = 16
Output: 4.00
Explanation:
Square root of 16 is 4, i.e. 42 = 16
Approach: The idea is to use logarithmic function to find the Nth root of K.
Let D be our Nth root of the K,
Then, 
Apply logK on both the sides –
=> 
=> 
=> 
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
double kthRoot( double n, int k)
{
return pow (k,
(1.0 / k)
* ( log (n)
/ log (k)));
}
int main( void )
{
double n = 81;
int k = 4;
printf ( "%lf " , kthRoot(n, k));
return 0;
}
|
Java
import java.util.*;
class GFG {
static double kthRoot( double n, int k)
{
return Math.pow(k, (( 1.0 / k) *
(Math.log(n) /
Math.log(k))));
}
public static void main(String args[])
{
double n = 81 ;
int k = 4 ;
System.out.printf( "%.6f" , kthRoot(n, k));
}
}
|
Python3
import numpy as np
def kthRoot(n, k):
return pow (k, (( 1.0 / k) *
(np.log(n) /
np.log(k))))
n = 81
k = 4
print ( "%.6f" % kthRoot(n, k))
|
C#
using System;
class GFG {
static double kthRoot( double n, int k)
{
return Math.Pow(k, ((1.0 / k) *
(Math.Log(n) /
Math.Log(k))));
}
public static void Main(String []args)
{
double n = 81;
int k = 4;
Console.Write( "{0:F6}" , kthRoot(n, k));
}
}
|
Javascript
<script>
function kthRoot(n, k)
{
return Math.pow(k, ((1.0 / k) *
(Math.log(n) /
Math.log(k))));
}
var n = 81;
var k = 4;
var x = kthRoot(n, k)
document.write(x.toFixed(6));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
18 Sep, 2022
Like Article
Save Article