Search code examples
c++sqrt

Top and bottom numbers of sqrt


So I am stuck or I confused my self with the following: I need to use a for loop to figure out the top and bottom numbers for the square root of a positive integer

ie:

Enter Num: 10
Top is 4
Bottom is 3

Enter Num: 16
Top is 4
Bottom is 3

Enter Num: 8
Top is 3
Bottom 2 

EDIT:

I have

for(int top =1;top >=num; top++)

does top >=num go there? I know 10^(1/2) is 3.16

Also how are the top and bottom found? I don't know how sqrt(10) top and bottom is 4 and 3... is this with fractions or with simplified squares? I am confused on this problem.

based on the help here is the answer

for(int top = 1; top <=num  ; top++) 
{
   if( top * top >= num)
   {
        cout << "Top is " << top ;
        cout << "\nBottom is " << (top-1) << endl;
        top =num +1;
    }
}

Solution

  • You could just loop over integers until you pass the square root:

    int bottom = 0;
    int top = 0;
    
    for (int i = 1; i <= num; ++i) {
        if (i * i > num) {
            top = i;
            break;
        }
        bottom = i;
    }