1 Star 0 Fork 0

jobily/TheAlgorithms-C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
NewtonSquareRoot.cs 888 Bytes
一键复制 编辑 原始数据 按行查看 历史
using System;
using System.Numerics;
namespace Algorithms;
public static class NewtonSquareRoot
{
public static BigInteger Calculate(BigInteger number)
{
if (number < 0)
{
throw new ArgumentException("Cannot calculate the square root of a negative number.");
}
if (number == 0)
{
return BigInteger.Zero;
}
var bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(number, 2)));
BigInteger root = BigInteger.One << (bitLength / 2);
while (!IsSquareRoot(number, root))
{
root += number / root;
root /= 2;
}
return root;
}
private static bool IsSquareRoot(BigInteger number, BigInteger root)
{
var lowerBound = root * root;
return number >= lowerBound && number <= lowerBound + root + root;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hubo/the-algorithms-c-sharp.git
git@gitee.com:hubo/the-algorithms-c-sharp.git
hubo
the-algorithms-c-sharp
TheAlgorithms-C-Sharp
master

搜索帮助