Wednesday, November 6, 2013

finding square root of a number without using sqrt method!!


Below code is to find the square root of a given integer number with out using sqrt math library function. Its very simple and brute force way to find the square root. This is not the best way, but one of the way to find the square root. The basic Idea is to squaring the numbers from one  and checking with the given number, if the given number is same the square of the number, then squared number is the square root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000

int find_sqrt(int number)
{
 int i,product = 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
   product = i*i;
   if(product==number)
     return i;
   else if(product>number)
     break;
 }
 return 0;
}

int main()
{
 int n=0,result=0;
 printf("enter the number to find the sqrt\n");
 scanf("%d",&n);
 if(n<0)
 {
  printf("enter only +ve integer value");
  return 0;
 }
 result = find_sqrt(n);
 if(result)
  printf("sqrt of %d is %d\n",n,result);
 else
  printf("not a proper value for finding the sqrt\n");
}

Output:


$ ./a.out
enter the number to find the sqrt
625
sqrt of 625 is 25

$ ./a.out
enter the number to find the sqrt
123
not a proper value for finding the sqrt

No comments:

Popular Posts