The problem of integer operation taking ceiling in "turn" C language

Source: Internet
Author: User

Original: http://blog.csdn.net/laciqs/article/details/6662472

-------------------------------------------------------

This topic from: "Linux C Programming One-stop learning"

Assuming that the variables x and n are two positive integers, we know that the result of the x/n expression is to take the floor, for example, if X is 17,n 4, then the result is 4. How do you write an expression if you want the result to be ceiling? For example X is 17,n is 4, then the result is 5;x is 16,n is 4, then the result is 4.

The answer to this question on the Internet only and proof, although we can prove the correctness of the answer is not know how to draw, this article fills this gap.

The derivation of a master (according to his original text):

Set X=kn+b,b∈ (0, N) and B∈z, when B=0,

(x+z)/n=k, namely (KN+Z)/n=k, according to the title, z Maximum is n-1;

When B≠0, (x+z)/n=k+1, that is (kn+b+z)/n=k+1, that is (b+z)/n=1, because b∈ (0, N) and b∈z, so B has a minimum value of 1, at this time Z is n-1, when B takes 2 o'clock, Z is n-2 ... When the b=n-1, Z=1, can be seen regardless of special circumstances, Z maximum is n-1, and when the b=n-1, z if the n-1, then (b+z)/n=2-2/n<2, that is (kn+b+z)/n<k+2, is still able to take ceiling. So no matter how z can be n-1, that is, z=n-1.

∈[1, n-1],∵[

So this expression should be written as: (x+n-1)/n

And from the above deduction process can be seen, for x%n=n-1 situation, as long as The X plus a 1 can take ceiling, such as 19%4=3, (19+1)/4=5.

The problem of integer operation taking ceiling in "turn" C language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.