In this exercise we are going to find out the square root of an integer if one is available else find its greatest square root after round off to an integer . For Example Square root of 9 is 3 and Square root of 15 will also be 3 since the square of 3 is 9 which is the greatest integer less than 15. Lets see the program.

#include<iostream> using namespace std; int findsqrt(int n) { int index=1,result=1; while(result<= n) { //store the square of the index and compare it with the input value //if it is greater than we reach the nearest element. result = (index*index); i++; } return (i-2); } int main() { int n; cout<<"

Enter the number to find its nearest square root"; cin>>n; int sqrt = findsqrt(n); cout<<sqrt; return 0; } Output:/a.out Enter the number to find its nearest square root: 8 2

Better Approach: Newton’s Method

#include<iostream> using namespace std; int ifissqrt(int n) { int x = n; int y = (x+1)/2; while(y < x) { x = y; y = (x+(n/x))/2; } return x; } int main() { int n; cout<<"

Enter the number to find its nearest square root"; cin>>n; int sqrt = ifissqrt(n); cout<<sqrt; return 0; } Output:/a.out Enter the number to find its nearest square root: 8 2

If you have any comment or feedback please leave a reply.