문제

The 'e' language has a 'ilog2' function but I need a 'ceiling of log2' type function - what's the best way to do this?

I could invoke a Perl through the system command and use POSIX::ceil...

도움이 되었습니까?

해결책

Invoking perl script might be computational expensive. Instead add 0.5 to log2 and typecast (not sure if e-language supports it) to integer.

Another try:

  Let y = ilog2(x);
  if ((x & x-1) == 0)  //Check if x is power of 2 
      return y; 
  else 
      return y+1;

다른 팁

I would have done something like this:

ceil_log2(in : uint): uint is {  
    var bottom := ilog2(in);  
    result = (in == ipow(2,bottom)) ? bottom : bottom + 1;  
};

If you don't mind doing it in real:

ceil_log2(in: uint): uint is {
  result = ceil(log10(in)/log10(2)).as_a(uint);
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top