Sale function using a limited set of arithmetic operators

Is it possible to calculate the ceiling (for example, ceil(2.12) = 3 ) with only a few available arithmetic operations: * - + / That is, without castings and other program tricks, only using the division / multi / sub / addition and comparison operators?

Explanations:

  • Complexity is important, but I will be happy to hear any decisions.
  • The module is unavailable.
  • The values ​​are positive.
  • Operations are not rounded.
  • With software tricks, I meant mod, bit level manipulation, etc.

Basically, I have a system that allows you to assign expressions to variables, where an expression can only contain the 4 arithmetic operations, comparisons, and loops listed above. For instance.

var x = if (A * (1.434 + 0.4325))> 54.4534), then 45.6 otherwise 43.435

and i would like to do

var x = CEIL (...)

+6
source share
1 answer

Perhaps, but do not expect any amazing results. The simplest algorithm ( th(x) ):

 frac = x; while(frac<0) frac+=1; while(frac>=1) frac-=1; if(frac>0) return x-frac+1; else return x; 

You can do better with a binary search ( th(log x) ):

 lower = 0; upper = 0; if(x>0){ upper = 1; while (x > upper) upper *= 2; }else if(x<0){ lower = -1; while (x > lower) lower *= 2; } while(upper-lower > 1){ //mid is guaranteed to be integer, since the upper-lower is a power of two mid = (upper+lower)/2; if(x > mid) lower = mid; else if(x < mid) upper = mid; else return mid; } return upper; // lower for floor 
+7
source

All Articles