Программа на C для поиска квадратного корня из заданного числа

Опубликовано: 10 Января, 2022

Для данного числа N задача состоит в том, чтобы написать программу на языке C, чтобы найти квадратный корень из данного числа N.

Примеры:

Input: N = 12 
Output: 3.464102

Input: N = 16 
Output:

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Метод 1. Использование встроенной функции sqrt () : функция sqrt () возвращает sqrt любого числа N.

Below is the implementation of the above approach:

C

// C program for the above approach
#include <math.h>
#include <stdio.h>
 
// Function to find the square-root of N
double findSQRT(double N) { return sqrt(N); }
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12;
 
    // Function call
    printf("%f ", findSQRT(N));
    return 0;
}
Output: 
3.464102

 

Метод 2: Использование двоичного поиска : этот подход используется для нахождения квадратного корня из заданного числа N с точностью до 5 знаков после запятой.

  1. Квадратный корень из числа N находится в диапазоне 0 ≤ squareRoot ≤ N. Инициализируйте start = 0 и end = number.
  2. Сравните квадрат среднего целого числа с заданным числом. Если оно равно числу, значит, мы нашли нашу составную часть, иначе ищите то же самое в левой или правой части середины в зависимости от условия.
  3. Найдя целую часть, мы найдем дробную часть.
  4. Инициализируйте переменную приращения на 0,1 и итеративно вычислите дробную часть до 5 знаков после запятой .
  5. Для каждой итерации измените приращение на 1/10 от предыдущего значения.
  6. Наконец, верните вычисленный ответ.

Below is the implementation of the above approach:

C

// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
 
// Function to find the square-root of N
float findSQRT(int number)
{
    int start = 0, end = number;
    int mid;
 
    // To store the answer
    float ans;
 
    // To find integral part of square
    // root of number
    while (start <= end) {
 
        // Find mid
        mid = (start + end) / 2;
 
        // If number is perfect square
        // then break
        if (mid * mid == number) {
            ans = mid;
            break;
        }
 
        // Increment start if integral
        // part lies on right side
        // of the mid
        if (mid * mid < number) {
          //first start value should be added to answer
            ans=start;
          //then start should be changed
            start = mid + 1;
        }
 
        // Decrement end if integral part
        // lies on the left side of the mid
        else {
            end = mid - 1;
        }
    }
 
    // To find the fractional part
    // of square root upto 5 decimal
    float increment = 0.1;
    for (int i = 0; i < 5; i++) {
        while (ans * ans <= number) {
            ans += increment;
        }
 
        // Loop terminates,
        // when ans * ans > number
        ans = ans - increment;
        increment = increment / 10;
    }
    return ans;
}
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12;
 
    // Function call
    printf("%f ", findSQRT(N));
    return 0;
}
Output: 
3.464099

 

Метод 3: Использование log2 () : Квадратный корень числа N можно вычислить с помощью log2 () как:

Let d be our answer for input number N, then  



Apply log2() both sides 

Therefore, 

d = pow(2, 0.5*log2(n)) 

Below is the implementation of the above approach:

C

// C program for the above approach
#include <math.h>
#include <stdio.h>
 
// Function to find the square-root of N
double findSQRT(double N) { return pow(2, 0.5 * log2(N)); }
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12;
 
    // Function call
    printf("%f ", findSQRT(N));
    return 0;
}
Output: 
3.464102

 

Хотите узнать о лучших видео и практических задачах, ознакомьтесь с Базовым курсом C для базового и продвинутого C.