Skip to content

Stack Overflow favorites – How can I ensure that a division of integers is always rounded up?

The best way to learn something is to teach it. I will try to do that here. The question is:

I want to ensure that a division of integers is always rounded up if necessary. Is there a better way than this? There is a lot of casting going on. 🙂

(int)Math.Ceiling((double)myInt1 / myInt2)


Eric Lippert, an excellent writer and a developer at Microsoft

Getting integer arithmetic correct is hard. As has been demonstrated amply thus far, the moment you try to do a "clever" trick, odds are good that you’ve made a mistake. And when a flaw is found, changing the code to fix the flaw without considering whether the fix breaks something else is not a good problem-solving technique. So far we’ve had I think five different incorrect integer arithmetic solutions to this completely not-particularly-difficult problem posted.

The right way to approach integer arithmetic problems — that is, the way that increases the likelihood of getting the answer right the first time – is to approach the problem carefully, solve it one step at a time, and use good engineering principles in doing so.

Start by reading the specification for what you’re trying to replace. The specification for integer division clearly states:

  1. The division rounds the result towards zero

  2. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs

  3. If the left operand is the smallest representable int and the right operand is –1, an overflow occurs. […] it is implementation-defined as to whether [an ArithmeticException] is thrown or the overflow goes unreported with the resulting value being that of the left operand.

  4. If the value of the right operand is zero, a System.DivideByZeroException is thrown.

What we want is an integer division function which computes the quotient but rounds the result always upwards, not always towards zero.

So write a specification for that function. Our function int DivRoundUp(int dividend, int divisor) must have behaviour defined for every possible input. That undefined behaviour is deeply worrying, so let’s eliminate it. We’ll say that our operation has this specification:

  1. operation throws if divisor is zero

  2. operation throws if dividend is int.minval and divisor is -1

  3. if there is no remainder — division is ‘even’ — then the return value is the integral quotient

  4. Otherwise it returns the smallest integer that is greater than the quotient, that is, it always rounds up.

Now we have a specification, so we know we can come up with a testable design. Suppose we add an additional design criterion that the problem be solved solely with integer arithmetic, rather than computing the quotient as a double, since the "double" solution has been explicitly rejected in the problem statement.

So what must we compute? Clearly, to meet our spec while remaining solely in integer arithmetic, we need to know three facts. First, what was the integer quotient? Second, was the division free of remainder? And third, if not, was the integer quotient computed by rounding up or down?

Now that we have a specification and a design, we can start writing code.

public static int DivRoundUp(int dividend, int divisor)
if (divisor == 0 ) throw ...
if (divisor == -1 && dividend == Int32.MinValue) throw ...
int roundedTowardsZeroQuotient = dividend / divisor;
bool dividedEvenly = (dividend % divisor) == 0;
if (dividedEvenly)
return roundedTowardsZeroQuotient;

// At this point we know that divisor was not zero 
// (because we would have thrown) and we know that 
// dividend was not zero (because there would have been no remainder)
// Therefore both are non-zero.  Either they are of the same sign, 
// or opposite signs. If they're of opposite sign then we rounded 
// UP towards zero so we're done. If they're of the same sign then 
// we rounded DOWN towards zero, so we need to add one.

bool wasRoundedDown = ((divisor > 0) == (dividend > 0));
if (wasRoundedDown)
return roundedTowardsZeroQuotient + 1;
return roundedTowardsZeroQuotient;

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

Is this clever? No. Beautiful? No. Short? No. Correct according to the specification? I believe so, but I have not fully tested it. It looks pretty good though.

We’re professionals here; use good engineering practices. Research your tools, specify the desired behaviour, consider error cases first, and write the code to emphasize its obvious correctness.And when you find a bug, consider whether your algorithm is deeply flawed to begin with before you just randomly start swapping the directions of comparisons around and break stuff that already works.


So typical.  A hello world App.  Except my assignment was to create two text fields, a label, and a button.

The two text fields allow a user to type in their first name and last name. The label will display the concatenated full name after the user presses the button.  Lets do this.

Coming from C++ and C#, I was confident of my programming prowess. I was unfortunately unprepared for the beast that is Xcode. Coming from the full featured Visual Studios and its rival, Eclipse, I was a culture shock to move to Xcode.

That is for another post.

Lets Get Started

First, create a project and pick View application not the Window application. We, apparently, aren’t prepared to attach views to window controllers. . .

Then in the header file (.h), define your two text boxes, a label, and an action (event handler for the rest of us).

@interface MyProjectAppDelegate : NSObject <UIApplicationDelegate> 
    IBOutlet UILabel *lblShowFullName;  // Label to Show your Full Name
     IBOutlet UITextField *txtFirstName;   // Text Box for getting the First Name
     IBOutlet UITextField *txtLastName;   // Text Box for getting the Last Name
     UIWindow *window;

@property (nonatomic, retain) IBOutlet UIWindow *window;

Interface Builder

Next go into Interface builder.  To get there, doubleclick your MainWindow.xib file in Xcode.

A Window should show up similar to this.

Start Dragging over the following:

  1. Two Text Fields
  2. One Label
  3. One Rectangle
Edit the Attributes (Property Window for the rest of us)

Now change the Attributes of the elements you dragged over.  If you don’t see the Attribute Window on the left, then just go to the Menu and click Tools then Attribute Inspector.

For the Text Fields:
  • Text – Make sure their Text Properties are cleared.  
  • Placeholder field – You can place some helpful text like “First name” into the Placeholder property.  The Placeholder property will be some faded text inside the text field that will give the user a visual cue of what to type into the Text field.
  • Return Key – Set it to Done. The user will see a “Done” key instead of a “Return” key
For the Label:
  • Text – Change the Text to something like “I will show your full name here!”
For the Round Rec Button
  • Text – Change the Text to something like “Say my name! Say my name!”

Connecting your instance variable to the objects in the Interface builder.

Remember the above code in the header file? Let’s look at it a bit more carefully.

IBOutlet UILabel *lblShowFullName;  // Label to Show your Full Name

Unlike Visual Studios, you have to predefine the variables here in the code. The IBOutlet is technically a pointer to an GUI element. This allows the program to interact with it.  It works the same way in Visual Studios, but Microsoft hid all the code or generated it for you.


This is an method of type IBAction which takes an incoming parameter of sender which is type id. Now, type id is just a generic object. Sender will be the GUI element that sent the message (event for the rest of us).  It is type IBAction so that the Interface Builder can find the cursed variable. 

To create the connections,  select the Round Rec Button and look at your Attribute Window. You should see  a list of events. The one you want to look for is Touch Up Inside.   Hold down Ctrl and drag a line from the Round Rec Button  to the FileOwner.  Your action showFullName should show up. Click it to create the connection.

You don’t need to hook up the other elements, since they aren’t sending events.

Implement your method

Now open up the implementation file (.m).

We are going to make the label display the full name by concatenating the strings.

       NSString *firstName = txtFirstName.text
       NSString *lastName = txtLastName.text
if([ firstName length] == 0 || [LastName length] == 0)
        lblShowFullName = [[NSString alloc] initWithFormat:@"Please fill in your name"]
        lblShowFullName.text = [NSString alloc] initWithFormat:@"%@ %@" firstName, lastName; 

Now what does this all do? We will go one line at a time.

       NSString *firstName = txtFirstName.text
       NSString *lastName = txtLastName.text

This grabs the text from the Text fields and stores them in string variables.

if([ firstName length] == 0 || [LastName length] == 0)

This is an IF statement.  It looks at the two string we just instanced and sees if either one of them has a length of zero, which means the user did not enter a first or last name.  

lblShowFullName = [[NSString alloc] initWithFormat:@"Please fill in your name"]

Changes the Label to say the message, “Please fill in your name.”

     lblShowFullName.text = [NSString alloc] initWithFormat:@"%@ %@" firstName, lastName;

Now the last part is an else statement. If either firstName or lastName has a length greater than zero(0), then we print their full name. The computer will fill in %@ with an arguement. Since we have two, separated by a space, we get the firstName followed by a space, followed by the lastName. 

Now hit build.  Weeeeeee


What we didn’t do was tell the Text Fields what to do when the user hits “Done.”

To get rid of the keyboard after the user hits “Done”, we need to go back into Interface Builder.  Hold Ctrl and Left-Click on each Text Field and drag them over to File’s Owner. Assign them to their appropriate delegates (txtFirstName, txtLastName).

Next we need to go into our implementation file (.m) and add in the following code:

-(BOOL)textFieldShouldReturn:(UITextField *)theTextField
    [theTextField resignFirstResponder];
    return YES;

The method send a message of type BOOL (boolean as in true or false) and they handle a message from a Text Field. It sends the message resignFirstResponder and returns YES.


Going Down like Steve Jobs

It’s weird, but I hope that’s how I go. Fast and doing what I love.

That’s what I typed into chat.

Response: wait… fast? Hadn’t he been battling cancer since, what, 2004? fast implies you don’t have a long drawn out illness than kills you very slowly over 7 years…

But you know, he worked day to day up until the day he stepped down. I’d say that while, not fast as instantaneous. It was fast in the sense he went full throttle. It would come as no surprise if he was working 70 hour weeks up til the day he stepped down.
We are all going to die sooner or later. So the cancer is a moot point.
We might as well die doing what we love for 70 hours a week.

It makes me wonder though.
Everyday, I feel I’m the only person that feels this way.
Because of my live fast, die fast attitude, I wonder and ask everyone:

"Will our generation ever live up to the same measure?"

Last generation created Bill Gates and Steve Jobs.
Darpa and the Internet.
Military hardware like the Nimitz class aircraft carrier along with Top Gun’s F-14, a plane that has never been shot down in air combat.
An Air Force that has never allowed an American force to come under air attack for over 50 years, well over half the time power flight has even existed.

The generation before that were hippies. But they walked on the Moon.

Before that generation, they stormed the sandy beaches of Normandy and fought the Battle of the Bulge.

Before that, over a million Europeans fought for family and country in the battle of Somme. A half a million young men on each side laid down their lives, not for money, not for retirement, but for a cause.

Crazy huh? People giving their lives for something you can’t touch.
Our generation so far has pumped out Facebook and social media.

Seriously, we better cure cancer or something.
Otherwise Nature will have no choice but to wipe us from the history books.

Hello world!

Welcome to After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can alway preview any post or edit you before you share it to the world.