forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NewtonSquareRoot.cs
37 lines (30 loc) · 888 Bytes
/
NewtonSquareRoot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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;
}
}