gpt4 book ai didi

c# - 快速整数平方根

转载 作者:行者123 更新时间:2023-11-30 22:06:22 32 4
gpt4 key购买 nike

有没有更快或更直接的计算整数平方根的方法:

http://en.wikipedia.org/wiki/Integer_square_root

在 C# 中为

private long LongSqrt(long value)
{
return Convert.ToInt64(Math.Sqrt(value));
}

?

最佳答案

如果您事先知道范围,则可以为平方值及其整数平方根创建查找索引。

下面是一些简单的代码:

// populate the lookup cache
var lookup = new Dictionary<long, long>();
for (int i = 0; i < 20000; i++)
{
lookup[i * i] = i;
}

// build a sorted index
var index = new List<long>(lookup.Keys);
index.Sort();

// search for a sample 27
var foundIndex = index.BinarySearch(27);
if (foundIndex < 0)
{
// if there was no direct hit, lookup the smaller value
// TODO please check for out of bounds that might happen
Console.WriteLine(lookup[index[~foundIndex - 1]]);
}
else
{
Console.WriteLine(lookup[foundIndex]);
}

// yields 5

如果您希望它更有效率,您可以通过创建一个并行的第二个列表来绕过字典查找。

关于c# - 快速整数平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23672069/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com