LeetCode Online Judge 题目C# 练习 - Sqrt(x)

本文介绍两种求解整数平方根的方法:二分查找法和牛顿迭代法。通过具体的C#与C语言代码实现,展示了如何高效地计算一个整数的平方根。

Implement int sqrt(int x).
Compute and return the square root of x.

 1         public static int Sqrt(int x)
 2         {
 3             if (x == 0) return 0;
 4 
 5             ulong x2 = (ulong)x;
 6             ulong l = 0;
 7             ulong r = (ulong)x;
 8             ulong mid;
 9 
10             while (l <= r)
11             {
12                 mid = l + (r - l) / 2;
13 
14                 //if Square(mid) < x < Square(mid + 1)
15                 if (mid * mid == x2 || (x2 > mid * mid && x2 < (mid + 1) * (mid + 1)))
16                     return (int)mid;
17                 else if (mid * mid > x2)
18                     r = mid - 1;
19                 else
20                     l = mid + 1;
21             }
22 
23             return -1;
24         }

代码分析:

  二分法找平方根。

  复习一下牛顿法求平方根。

  xk+1 = (xk + n / xk) / 2   (X0 = 1)

  C code:

 1 float Sqrt(int n)
 2 {
 3     float x = 1;
 4     //收敛1000次,越多越准
 5     for(int i = 1; i <= 1000; i++)   
 6     {
 7         x = (x + n / 2) / 2;
 8     }
 9     
10     return x;
11 }

转载于:https://www.cnblogs.com/etcow/archive/2012/10/17/2728741.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值