What is the easiest way to calculate the smallest integer greater than or equal to a / b?

r, aand bare integers.

I need the cheapest calculation since the critical part of the code. I found:

r = (a / b) + (((a % b) != 0) ? 1 : 0);

if b is a power of 2, then a / bcan be replaced bya >> log2(b)

and a % bwith a & (b-1), which should save a lot of time on the calculation.

Do you know any better solution?

+3
source share
7 answers
val r = (a + b - 1) / b

For example:

scala> for(a <- 1 to 10; b <- 1 to a) println("a: "+a+"\tb: "+b+"\tr: "+((a+b-1)/b))
a: 1    b: 1    r: 1
a: 2    b: 1    r: 2
a: 2    b: 2    r: 1
a: 3    b: 1    r: 3
a: 3    b: 2    r: 2
a: 3    b: 3    r: 1
a: 4    b: 1    r: 4
a: 4    b: 2    r: 2
a: 4    b: 3    r: 2
a: 4    b: 4    r: 1
a: 5    b: 1    r: 5
a: 5    b: 2    r: 3
a: 5    b: 3    r: 2
a: 5    b: 4    r: 2
a: 5    b: 5    r: 1
a: 6    b: 1    r: 6
a: 6    b: 2    r: 3
a: 6    b: 3    r: 2
a: 6    b: 4    r: 2
a: 6    b: 5    r: 2
a: 6    b: 6    r: 1
a: 7    b: 1    r: 7
a: 7    b: 2    r: 4
a: 7    b: 3    r: 3
a: 7    b: 4    r: 2
a: 7    b: 5    r: 2
a: 7    b: 6    r: 2
a: 7    b: 7    r: 1
a: 8    b: 1    r: 8
a: 8    b: 2    r: 4
a: 8    b: 3    r: 3
a: 8    b: 4    r: 2
a: 8    b: 5    r: 2
a: 8    b: 6    r: 2
a: 8    b: 7    r: 2
a: 8    b: 8    r: 1
a: 9    b: 1    r: 9
a: 9    b: 2    r: 5
a: 9    b: 3    r: 3
a: 9    b: 4    r: 3
a: 9    b: 5    r: 2
a: 9    b: 6    r: 2
a: 9    b: 7    r: 2
a: 9    b: 8    r: 2
a: 9    b: 9    r: 1
a: 10   b: 1    r: 10
a: 10   b: 2    r: 5
a: 10   b: 3    r: 4
a: 10   b: 4    r: 3
a: 10   b: 5    r: 2
a: 10   b: 6    r: 2
a: 10   b: 7    r: 2
a: 10   b: 8    r: 2
a: 10   b: 9    r: 2
a: 10   b: 10   r: 1

This suggests that athey bare positive. If they are negative, it depends on whether the division is symmetric or divided (modern languages ​​and platforms are symmetrical) and the signal aand b.

a*b >= 0, . a*b < 0, a / b .

+29

"", "". ? .

, , , ( ceil), - , ( )

, log2 - . : .

+5

:

(a - 1) / b + 1;

, , 0 . , , .

+3

modulo % n = a - (n * (a/n);

, ,

const int div = a / b;
r = div + (((a - (n * div)) != 0) ? 1 : 0 );

, div 2.

: b , " " ( ), . .

+1

, , ( ) . , # Math.Ceiling(5/2) 3.

0

, ANS Forth, ...

: div ( a b -- r)
  FM/MOD     \ a b -- q rest
  IF 1+ THEN \ q rest -- r
;
0

, . , , , int- .

- DIVMOD, . , .

-4

Source: https://habr.com/ru/post/1715635/


All Articles