For a given number find the square root using log function. Number may be int, float or double.
Examples:
Input : n = 9
Output : 3
Input : n = 2.93
Output : 1.711724
We can find square root of a number using sqrt() method:
C++
#include<bits/stdc++.h>
int main(void)
{
double n = 12;
printf("%lf ", sqrt(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
double n = 12;
System.out.println(Math.sqrt(n));
}
}
|
Python3
import math
if __name__=='__main__':
n = 12
print(math.sqrt(n))
|
C#
using System;
class GFG
{
public static void Main()
{
double n = 12;
Console.Write(Math.Sqrt(n));
}
}
|
PHP
<?php
$n = 12;
echo sqrt($n);
?>
|
Javascript
<script>
var n = 12;
document.write(Math.sqrt(n).toFixed(6));
</script>
|
Time complexity: O(log2n), for using sqrt() function.
Auxiliary space: O(1)
We can also find square root using log2() library function:
C++
#include<bits/stdc++.h>
double squareRoot(double n)
{
return pow(2, 0.5*log2(n));
}
int main(void)
{
double n = 12;
printf("%lf ", squareRoot(n));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static double squareRoot(double n)
{
return Math.pow(2, 0.5 * (Math.log(n) /
Math.log(2)));
}
public static void main (String[] args)
{
double n = 12;
System.out.println(squareRoot(n));
}
}
|
Python
import math
def squareRoot(n):
return pow(2, 0.5 * math.log2(n))
n = 12
print(squareRoot(n))
|
C#
using System;
public class GFG{
static double squareRoot(double n)
{
return Math.Pow(2, 0.5 * (Math.Log(n) /Math.Log(2)));
}
static public void Main (){
double n = 12;
Console.WriteLine(squareRoot(n));
}
}
|
PHP
<?php
function squareRoot($n)
{
return pow(2, 0.5 * log($n, 2));
}
$n = 12;
echo squareRoot($n);
?>
|
Javascript
<script>
function squareRoot(n)
{
return Math.pow(2, 0.5 * (Math.log(n) /Math.log(2)));
}
let n = 12;
document.write(squareRoot(n).toFixed(15));
</script>
|
Time complexity: O(log2log2N), complexity of using log(N) is log(logN), and pow(x,N) is log(N), so pow(2,0.5*log(n)) will be log(logN).
Auxiliary space: O(1)
How does the above program work?
let d be our answer for input number n
then n(1/2) = d
apply log2 on both sides
log2(n(1/2)) = log2(d)
log2(d) = 1/2 * log2(n)
d = 2(1/2 * log2(n))
d = pow(2, 0.5*log2(n))
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!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
25 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...