-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqrt and any nth root using binary search.txt
84 lines (66 loc) · 1.45 KB
/
sqrt and any nth root using binary search.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
#include <bits/stdc++.h>
using namespace std;
double esp = 1e-7;
int main()
{
double x;
cout << "Enter a number which you want to find squere root of that number : " << endl;
cin >> x;
double low = 1;
double high = x;
double mid;
while(high - low > esp)
{
mid = (high+low)/2;
if((mid*mid) < x) // this mid*mid denote for square root
{
low = mid;
}
else
{
high = mid;
}
}
cout << "The square root of " << x << " is " << high << endl;
}
*/
// if we have to find the nth root of any number so above programe is use;
#include <bits/stdc++.h>
using namespace std;
double esp = 1e-7;
double multiply(double mid , int n)
{
double ans = 1;
for(int i = 0 ; i < n ; i++)
{
ans *= mid;
}
return ans;
}
int main()
{
double x;
cout << "Enter a number which you want to find root of that number : " << endl;
cin >> x;
int n;
cout << "Enter the power of given numebr : " << endl;
cin >> n;
double low = 1;
double high = x;
double mid;
while(high - low > esp)
{
mid = (high+low)/2;
if((multiply(mid,n)) < x) // this mid*mid denote for square root
{
low = mid;
}
else
{
high = mid;
}
}
cout << "The "<< n <<" th root of " << x << " is " << high << endl;
}
// Time complexity p*log(N*(10^d))