二进制搜索算法无重复

时间:2014-03-23 22:58:59

标签: c# math logic biginteger

我试图编写一个函数,允许以二进制搜索模式处理0-n中的所有数字,而不重复。

以下是我瞄准的一个例子:

get(bigint max, bigint point)

get(10000, 0) = 0   //start
get(10000, 1) = 10000   //end

get(10000, 2) = 5000    //middle

get(10000, 3) = 2500    //(max/4) * 1
// Skip 500 as we've already done that one
get(10000, 4) = 7500    //(max/4) * 3

get(10000, 5) = 1250    //(max/8) * 1
// Skip 250 as we've already done it
get(10000, 6) = 3750    //(max/8) * 3
// Skip 500 as we've already done that one
get(10000, 7) = 6250    //(max/8) * 5
// Skip 750 as we've already done that one
get(10000, 8) = 8750    //(max/8) * 7

我认为这是一种启发式方法,因为所有乘数都是奇数,并且使用2的幂作为除数。

考虑到几乎所有的数字都是BigIntegers,我怎样才能最有效地做到这一点?

1 个答案:

答案 0 :(得分:1)

这是一个算法(伪代码)

function get(max, point)
  if point == 0 then 
    return 0
  if point == 1 then
    return max
  x = 2*point-1
  y = high_power_of_two(x)  // e.g., high_power_of_two(13) == 8
  return (x-y)*(max/y)