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

- 06-27-2010truetrini20C++problem to solve
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

- 06-27-2010Salem
- 06-28-2010Dante Wingates
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);

}

- 06-28-2010g4j31a5
@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.

- 06-28-2010iMalc
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. - 06-28-2010truetrini20
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

- 06-29-2010g4j31a5
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. - 06-29-2010iMalc
- 06-29-2010phantomotap
- 06-29-2010g4j31a5

http://en.wikipedia.org/wiki/Fast_inverse_square_root

Well, he said without math library so... :)