ok im trying to write a c++ program that will determine the square root of 138 without using a calculator or the math library. any suggestions
Printable View
ok im trying to write a c++ program that will determine the square root of 138 without using a calculator or the math library. any suggestions
Here, I found this searching my old codes... I wrote it when I was still learning C and C++... Yes, I keep my old codes and the codes I find interesting today, just to compare to the code of tomorrow.
I remember that I wrote it using a square root algorithm I found on the web... But I dont remember very well how it works... Anyway, here it is.. Hope it helps in some way:
Code:#include <stdio.h>
int getroot(int value)
{
int count = 0;
for(count = 0; (count * count) != value &&
(count * count) <= value; count++)
continue;
if((count * count) == value)
return(count);
else
return(0);
}
double fullroot(double value)
{
double count;
double reval;
for(count = 0; (count * count) != value &&
(count * count) <= value; count++)
continue;
if((count * count) == value)
return(count);
else
{
reval = (count - 1) + 0.1;
for(; (reval * reval) < value && reval != (reval + 0.999998);
reval = reval + 0.000001)
continue;
return((reval - 0.000001));
}
}
int main(int argc, char **argv)
{
printf("Square root of 16:%d\n", getroot(16));
printf("Square root of 10:%f", fullroot(10));
getchar();
return(0);
}
@Dante: you know, I understand you meant well. but you shouldn't help those who violated the Homework Policy with a fully working code. Don't give them a fish but teach them how to fish instead. Give them a fishing pole, a net, a harpoon, a poison-for-fishing, a tesla-coil-to-electrocute-those-fishes, etc. If you know what I mean.
Do not use Dante's code. It is very poor.
A propper solution such as the babylonian square root is far more efficient, more accurate, easier to understand, and much less code.
Thanks for the help @ dante and i understand what you're saying @ g4j31a5, all i wanted was a little direction not a full layout but i know @ dante was just trying to help
Or quake's fast square root. :D
I'm glad you understand. Well I can give you a slight hint. Mathematical functions are derived from bitwise operations. So if you understand the concept of bitwise operations like "AND", "OR", "XOR", bitshifting, etc, maybe you can make your own function.
http://en.wikipedia.org/wiki/Fast_inverse_square_root
Well, he said without math library so... :)