Home > Backend Development > C++ > How to Calculate the Ceiling of Integer Division in C/C without Multiplication or Floating-Point Operations?

How to Calculate the Ceiling of Integer Division in C/C without Multiplication or Floating-Point Operations?

Susan Sarandon
Release: 2024-11-22 08:48:14
Original
988 people have browsed it

How to Calculate the Ceiling of Integer Division in C/C   without Multiplication or Floating-Point Operations?

Ceiling of Integer Division without Multiplication or Floating-Point Casting

In C and C , integer division (x/y) returns the floor of the result. To calculate the ceiling instead, avoiding floating-point casting and additional multiplication, consider the following methods:

1. Using (x y - 1) / y:

unsigned int x, y, q;
// Round up
q = (x + y - 1) / y;
Copy after login

This formula ensures that the ceiling is computed, as it adds 1 before performing division.

2. Avoiding Overflow in (x y):

To prevent integer overflow when adding x and y, an alternative method is:

q = 1 + ((x - 1) / y); // if x != 0
Copy after login

This formulation effectively increments the ceiling by 1, except when x is 0, where it remains 0.

The above is the detailed content of How to Calculate the Ceiling of Integer Division in C/C without Multiplication or Floating-Point Operations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template