Find Cube root of a number using Log function
Given the number N, the task is to find the cube root using the log function.
Examples:
Input: N = 8
Output: 2.000000
Input: N = 27
Output: 3.000000
Approach: To solve the problem mentioned above we will use log() function, according to the following formula:
Let cube root of N be d.
=> ?N = d
=> N(1/3) = d
Now, apply log on both sides:
log3 (N(1/3)) = log3 (d)
=> log3 (d) = 1/3 * log3 (N)
=> d = 3(1/3 * log3 (N))
Below is the implementation of the above problem:
C++
#include <bits/stdc++.h>
double cubeRoot( double n)
{
double ans = pow (3, (1.0 / 3)
* ( log (n) / log (3)));
return ans;
}
int main()
{
double N = 8;
printf ( "%.2lf " , cubeRoot(N));
return 0;
}
|
Java
class GFG{
static double cubeRoot( double n)
{
double ans = Math.pow( 3 , (( 1.0 / 3 ) *
(Math.log(n) /
Math.log( 3 ))));
return ans;
}
public static void main(String[] args)
{
double N = 8 ;
System.out.printf( "%.2f" , cubeRoot(N));
}
}
|
Python3
import numpy as np
def cubeRoot(n):
ans = pow ( 3 , ( 1.0 / 3 ) * (np.log(n) /
np.log( 3 )))
return ans
N = 8
print ( "%.2f" % cubeRoot(N))
|
C#
using System;
class GFG{
static double cubeRoot( double n)
{
double ans = Math.Pow(3, ((1.0 / 3) *
(Math.Log(n) /
Math.Log(3))));
return ans;
}
public static void Main(String[] args)
{
double N = 8;
Console.Write( "{0:F2}" , cubeRoot(N));
}
}
|
Javascript
<script>
function cubeRoot( n)
{
let ans = Math.pow(3, (1.0 / 3)
* (Math.log(n) / Math.log(3)));
return ans;
}
let N = 8;
document.write( cubeRoot(N).toFixed(2));
</script>
|
Time complexity: O(log2(log3n))
Auxiliary space: O(1)
Last Updated :
14 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...