写一个sqrt函数的方法

题目链接:https://nanti.jisuanke.com/t/17
样例输入
1 2 3 4 5 6 7 8 9
样例输出
1 1 1 2 2 2 2 2 3
1.普通方法-会超时!

#include<stdio.h>
#include<iostream>
using namespace std;
int sqr(int n)
{
    int i;
    for (i = 1; i*i <= n; i++);
    return i - 1;
}
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
        printf("%d\n", sqr(n));
    return 0;
}

2.位运算-会超时!

#include<stdio.h>
#include<iostream>
using namespace std;
int sqr(int n)
{
    int i = 1;
    int tmp = 1;
    if (n <= 1) return n;
    while (n>=tmp)
    {
        i++;
        int cmp = i << 1;
        tmp += cmp - 1;
    }
    return i-1;
}
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
        printf("%d\n", sqr(n));
    return 0;
}

3.为什么会想到二分???

#include<stdio.h>
#include<iostream>
int sqrt(int n)
{
    int low = 0;
    int high = n;
    while (low <= high)
    {
        //防止溢出
        long mid = (low + high) / 2;
        if (mid*mid == n)
            return mid;
        else if (mid*mid < n)
            low = (mid + 1);
        else
            high = mid - 1;
    }
    return high;
}
int main()
{
    int n;
    while(scanf("%d", &n)!=EOF)
        printf("%d\n", sqrt(n));
    return 0;
}

4.牛顿法
这里写图片描述

这里写图片描述

#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int sqr(int n)
{
    double t = 1.0;
    while (fabs(t*t-n)>1e-6)
    {
        t = (t + n / t) / 2;
    }
    return t;
}
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
        printf("%d\n", sqr(n));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_42424364/article/details/82381039