Integer Square Root

I don't even know how to start this one.

Here is the problem: Ask the user for a number between 2 and 1000. Calculate the integer square root by calculating the square of every number from 1 until the square of the number is more than the number entered. The previous number is the integer square root. For example, if the user enters 15, your program would calculate 1x1 = 1, 2x2 = 4, 3x3 = 9, 4x4 = 16 -- since 16 is too high, the integer square root of 15 is 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int number = 0;
int squares = 0;
std::cout << "Enter a number " << std::endl;
std::cin >> number;

for ( ;; ++squares )
{
      if ( squares * squares > number )
      {
          std::cout << squares*squares << " is too high the square root of " << number << " is " << squares - 1 << std::endl;
          break;
      }
}
Almost the same thing, but with the 2 and 1000 check.

http://cpp.sh/6dme
Last edited on
thats what you said in your thread.
you can do it now yourself goodluck :)
1
2
3
4
5
6
7
8
	int num;
	cin >> num;
	if(num<2 || num>1000) cout << "range error";
	int root;
	for(int i=1; num>=i*i; i++){		
		root=i;		
	}		
	cout << root;
@GreatBlitz but how do I get to show like this:

"Enter a number between 2 and 1000 inclusive: 18
1 x 1= 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
The integer square root of 18 is 4
Press any key to continue"

I got it to show what the square root is but how do I get to show the process?
std::cout << i << " * " << i << " " << i*i << std::endl;
Last edited on
I tried what you did already. What I'm saying it needs to show all like in my example above. So for 4 it should be:

1 x 1 = 1
2 x 2 = 4
The integer for square root of 4 is 2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{		
	int num;
	cout << "number = ";
	cin >> num;
	if(num<2 || num>1000) cout << "range error";
	int root;
	for(int i=1; num>=i*i; i++){			
		root=i;	
		cout << i << "*" << i << "= " << i*i << "\n";
	}
			
	cout << "integer root = " << root << "\n";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
int main() {
    std::cout << "Enter a number between 2 and 1000" << std::endl;

    int x;
    std::cin >> x;

    if (x >= 2 && x <= 1000) {
        for (int i = 1; i <= 31; ++i){
            std::cout << i << " x " << i << " is " << i*i << std::endl;
            if (((i*i) < x) && (((i+1)*(i+1)) > x)){
                std::cout << "The integer square root of " << x << " is " << i << std::endl;
                return 0;
            }
        }
    }

    else {
        std::cout << "Number must be between 2 and 1000!" << std::endl;
        return -1;
    }
}


@calisabeth same code, but with the

1 x 1= 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16

put in. Also made 2 and 1000 inclusive.
Last edited on
Topic archived. No new replies allowed.