2

Ceil and floor functions in C++ without using std::ceil or std::floor

 1 year ago
source link: https://codeforces.com/blog/entry/109514?f0a28=1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Well, instead of using built-in functions in the language it's better if you know how they work and use them in your own way manually

I wondered how the ceil and floor function works, especially in the division .

One of my friends advised me to use this formula to find the ceil(a, b) so in code : int ceil = (a + b - 1) / 2; this works perfectly fine with positive

But unfortunately, this formula is not accurate, as it does not work with negative numbers

Here is a counter example but with this formula we get different result = , so we can't rely on this with negative numbers

Now let's focus on floor for a bit, you maybe think floor(a,b) is so simple as int floor = (int)(a/b);

And I believed it and was happy because it is so simple. But the misunderstanding happened because I used to think that division of integers in programming is equal to rounding down the result

While the right was Truncating division Truncating division is division where a fractional result is converted to an integer by rounding towards zero.

Or in another way integer division is just omitting the fraction part not flooring the value so we can't say that floor is equal to because for example

Anyway.. I tried to make that function again by myself without using the datatype double

int myfloor(int a, int b) {
    if (a % b == 0) return (a / b);
    bool negative = (a < 0) ^ (b < 0);
    return a / b - negative;
}

int myceil(int a, int b) {
    if (a % b == 0) return (a / b);
    bool positive = !((a < 0) ^ (b < 0));
    return a / b + positive;
}

If there are any better or shorter ways, please write them in the comments. This is the reason for my post (Seeking better solutions)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK