Hey guys,
I was trying to help someone with a problem involving finding if a number is a perfect square. I came to the conclusion that
Given that square can have any beginning point and ending point within the numeric_limits. His teacher then responded. Due to truncation of sqrt() when dealing with alot of digits you will "miss" some perfect squares. This didn't make sense to me. Any number that requires a truncation of sqrt() wouldn't be a perfect square. To try and demonstrate the error that the teacher said would occur I coded a small program.Code:int root; int square; for(square = 0; square < 100; square++) { root = sqrt(square); if(root * root == square) { cout<<square; } }
As I expected the result still finds the first perfect square counting down from the numberic_limits of a int. Can anyone demonstrate how the method used would exclude a perfect square that is within the limits of an int? Further why would sqrt() be in a standard library math.h if it wasn't dependable?Code:#include <iostream> #include <stdio.h> #include <limits> #include <math.h> using namespace std; double y; int rootfound; int main(void) { // start at the max value of an integer and find the first square using my method for(int x = numeric_limits<int>::max(); x > 0; x--) { int z = (int)sqrt(x); if(z*z == x) { rootfound = z; cout<<"found a perfect square: "<<x<<endl; cout<<"its root is "<<z<<endl; x = 0; } } // now test the next perfect square and see if it is over the numeric limits of // an integar rootfound++; cout<<"testing the next number up from this root: "<<endl; cout<<"The new root to work with is "<<rootfound<<endl; cout<<"Its perfect square is "<<(rootfound*rootfound)<<endl; if((rootfound*rootfound) < 0) { cout<<"this square was over the numeric limits so we found the first square root lower than limits"<<endl; } else cout<<"this square was under the number limits so the sqrt() function caused us to miss a perfect square"<<endl; system("pause"); }



LinkBack URL
About LinkBacks



