Skip to content

Commit 125289e

Browse files
added solution to calculate square root- issue div-bargali#865
1 parent 149bc6d commit 125289e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <math.h> //for log10(), fabs(), pow()
3+
4+
using namespace std;
5+
6+
#define DBL_EPSILON 2.2204460492503131e-16
7+
8+
//These 2 functions will accept user input and return the resulting Square Root of that user input
9+
10+
//Iterative Function
11+
double sqrtIterative(double x)
12+
{
13+
double sqrt = x * pow(0.3, log10(x));
14+
for (int i = 0; i < 5; i++)
15+
sqrt = (sqrt + (x / sqrt)) * 0.5;
16+
return sqrt;
17+
}
18+
19+
//Recursive function
20+
double sqrtRecursive(double num, double prev)
21+
{
22+
double next = (prev + num / prev) / 2;
23+
if (fabs(next - prev) < DBL_EPSILON * next)
24+
return next;
25+
return sqrtRecursive(num, next);
26+
}
27+
28+
int main(void)
29+
{
30+
31+
//Iterative Function
32+
cout << "*************************Iterative Function*************************" << endl;
33+
cout << "Please enter a number : ";
34+
double it;
35+
cin >> it;
36+
double answerIterative = sqrtIterative(it);
37+
cout << "The Square Root is : " << answerIterative << endl
38+
<< endl;
39+
40+
//Recursive Function
41+
cout << "*************************Recursive Function*************************" << endl;
42+
cout << "Please enter a numbers : ";
43+
double rc;
44+
cin >> rc;
45+
double answerRecursion = sqrtRecursive(rc, 1);
46+
cout << "The Square Root is : " << answerRecursion << endl;
47+
}

0 commit comments

Comments
 (0)