Wednesday, June 19, 2013

Find Square root without using standard library funtion

Hi guys,

Here I have a program which is used to find out the square root of a number without using standard library function. This method is known as Babylonian method. You can understand the algo part with this link. The only difference which I included is about the first guess. I am taking first guess as the lowest number which have ’0' as half of the original number’s length. I think I may have confused you. so here is the example if you want to find out the root of 1600, so I will start with 10. you will have better idea once you will go through the code.


#include
int calculateStarter(int n);
 
main()
{
    int number;
    int answer, guess, temp;
    printf("Enter the number for square root\n");
    scanf("%d",&number);
    printf("here start the processing\n");
    guess = calculateStarter(number);
    while(1)
    {
        answer = number/guess;
         
        temp = (answer + guess)/2;
        printf("number = %d and guess = %d and temp = %d\n",number,guess,temp);
        if(guess - answer < 1)
            break;
        guess = temp;
    }
    printf("so the answer is %d\n",temp);
}
 
int calculateStarter(int n)
{
     
    int temp =1;
    int count=0;
    printf("In the calculate method\n");
    while (n /10 != 0)
    {
        count++;
        n = n/10;
    }
    //if(count%2 == 0)
    count = count/2 + 1;
     
    while(count >0)
    {
        temp = temp*10;
        count--;
    }
    printf("so the guess is %d\n",temp);
    return temp;
}
   

No comments: