Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: All
Apr 18, 2000

A Smart Ceiling for a Ratio of Two Integers

I often use the following trick in my code.

Let "a" and "b" be real positive numbers. You want to find the smallest integer greater than or equal to "a/b". Perhaps your code looks like:
 
#include <math.h>
double a, b;
long c;
c = (long) ceil( a / b );
Now, the question remains the same, but your numbers "a" and "b" happen to be integers. You can write:
 
#include <math.h>
long a, b, c;
c = (long) ceil( (double)a/(double)b );
However, there is a more elegant and efficient solution:
 
long a, b, c;
c = (a - 1) / b + 1;
Eugene Zak
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date