Visual C++ - Square Root of a Given Number
You can solve the problem in two ways with out using the library function sqrt(...) defined in math.h header file.
Method 1 - Like binary search, have a minimum and maximum possible values. Do the square operation and compare the result. Then adjust minimum or maximum until we find the correct sqrt of the given number. NOTE: This is NOT a perfect square root and it has got accuracy of 4 decimal points. Method 1 is explained on this page.
Method 2 - The traditional way of doing with out calculator or any assumption is using the algorithm. It will be perfect square root up to N number of decimal points meaning the limitation of float and double.Click here to go to algorihmic source code for finding square root.
Source Code
#include <stdio.h>
#include <iostream>
#include <tchar.h>
#include <math.h>
double SQRTByGuess(double num)
{
// Assume that the number is less than 1,000,000. so that the maximum of SQRT would be 1000.
// Lets assume the result is 1000. If you want you can increase this limit
if(num < 0)
{
std::cout << "Negative numbers are not allowed";
return -1;
}
else if(num == 0)
return 0;
double min = 0, max = 1000;
double answer = 0;
double test = 0;
while(1)
{
test = (min + max) / 2;
answer = test * test;
if( num > answer)
{
// min needs be moved
min = test;
}
else if(num < answer)
{
// max needs be moved
max = test;
}
if(num == answer)
break;
if(num > (answer - 0.0001) &&
num < (answer + 0.0001))
break;
}
return test;
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 1; i <= 100; i += 3)
{
double t = SQRTByGuess(i);
char buf[128];
sprintf(buf, "\nSQRT(%d) = %.4lf, %.4lf", i, t, sqrt((double)i));
std::cout << buf;
}
return 0;
}
Output
SQRT(1) = 1.0000, 1.0000
SQRT(4) = 2.0000, 2.0000
SQRT(7) = 2.6458, 2.6458
SQRT(10) = 3.1623, 3.1623
SQRT(13) = 3.6055, 3.6056
SQRT(16) = 4.0000, 4.0000
SQRT(19) = 4.3589, 4.3589
SQRT(22) = 4.6904, 4.6904
SQRT(25) = 5.0000, 5.0000
SQRT(28) = 5.2915, 5.2915
SQRT(31) = 5.5678, 5.5678
SQRT(34) = 5.8309, 5.8310
SQRT(37) = 6.0828, 6.0828
SQRT(40) = 6.3246, 6.3246
SQRT(43) = 6.5574, 6.5574
SQRT(46) = 6.7823, 6.7823
SQRT(49) = 7.0000, 7.0000
SQRT(52) = 7.2111, 7.2111
SQRT(55) = 7.4162, 7.4162
SQRT(58) = 7.6158, 7.6158
SQRT(61) = 7.8102, 7.8102
SQRT(64) = 8.0000, 8.0000
SQRT(67) = 8.1854, 8.1854
SQRT(70) = 8.3666, 8.3666
SQRT(73) = 8.5440, 8.5440
SQRT(76) = 8.7178, 8.7178
SQRT(79) = 8.8882, 8.8882
SQRT(82) = 9.0554, 9.0554
SQRT(85) = 9.2195, 9.2195
SQRT(88) = 9.3808, 9.3808
SQRT(91) = 9.5394, 9.5394
SQRT(94) = 9.6954, 9.6954
SQRT(97) = 9.8489, 9.8489
SQRT(100) = 10.0000, 10.0000
|