I'm playing around with some calculations in a program I'm writing. Although my problem may seem obscure and perhaps avoidable, it's not, and even if it is, I'd rather not avoid it for now :-D
The problem is that I have a huge number (thousands of digits, maybe millions at some point) which I need to find an approximate SQRT for. I'm using System.Numerics.BigInteger, I'm need the approximation to be less than or equal to the real SQRT. For example, if the number provided was 100, I'd be happy with 7, 8, 9 or 10, but not 11.
Current Code:
public static BigInteger IntegerSqrt(BigInteger n)
{
var oldValue = new BigInteger(0);
BigInteger newValue = n;
while (BigInteger.Abs(newValue - oldValue) >= 1)
{
oldValue = newValue;
newValue = (oldValue + (n / oldValue)) / 2;
}
return newValue;
}
Whilst this gives me the right answer (so far as I can tell), it's crazy slow as it's trying to get a precise answer.
If getting the cube-root, or anything else like that would be faster, I'd be happy with that. Also, yes, I know finding square roots quickly can make you lots of money, not really what I'm trying to do though, I just want a quick approximation...
Any help you could give me would be great!
Edit - Gabe
This is the updated IntegerSqrt function I am using which doesn't appear to work any quicker.
public static BigInteger IntegerSqrt(BigInteger n)
{
var oldValue = n.RoughSqrt();
BigInteger newValue = n;
while (BigInteger.Abs(newValue - oldValue) >= 1)
{
oldValue = newValue;
newValue = (oldValue + (n / oldValue)) / 2;
}
return newValue;
}
Edit 2
Is this what you were thinking? - I ran this for 30 minutes on a sample large number (50k digits) and it looped around 100 times without completing. I feel as though I'm missing something...
public static BigInteger IntegerSqrt(BigInteger n)
{
var oldValue = new BigInteger(0);
BigInteger newValue = n.RoughSqrt();
int i = 0;
while (BigInteger.Abs(newValue - oldValue) >= 1)
{
oldValue = newValue;
newValue = (oldValue + (n / oldValue)) / 2;
i++;
}
return newValue;
}