Neatest / Fastest Algorithm for Smallest Positive Number - c++

Simple question - In c++, what's the neatest way of getting which of two numbers (u0 and u1) is the smallest positive number? (that's still efficient)
Every way I try it involves big if statements or complicated conditional statements.
Thanks,
Dan
Here's a simple example:
bool lowestPositive(int a, int b, int& result)
{
//checking code
result = b;
return true;
}
lowestPositive(5, 6, result);

If the values are represented in twos complement, then
result = ((unsigned )a < (unsigned )b) ? a : b;
will work since negative values in twos complement are larger, when treated as unsigned, than positive values. As with Jeff's answer, this assumes at least one of the values is positive.
return result >= 0;

I prefer clarity over compactness:
bool lowestPositive( int a, int b, int& result )
{
if (a > 0 && a <= b) // a is positive and smaller than or equal to b
result = a;
else if (b > 0) // b is positive and either smaller than a or a is negative
result = b;
else
result = a; // at least b is negative, we might not have an answer
return result > 0; // zero is not positive
}

Might get me modded down, but just for kicks, here is the result without any comparisons, because comparisons are for whimps. :-)
bool lowestPositive(int u, int v, int& result)
{
result = (u + v - abs(u - v))/2;
return (bool) result - (u + v + abs(u - v)) / 2;
}
Note: Fails if (u + v) > max_int. At least one number must be positive for the return code to be correct. Also kudos to polythinker's solution :)

unsigned int mask = 1 << 31;
unsigned int m = mask;
while ((a & m) == (b & m)) {
m >>= 1;
}
result = (a & m) ? b : a;
return ! ((a & mask) && (b & mask));
EDIT: Thought this is not so interesting so I deleted it. But on the second thought, just leave it here for fun :) This can be considered as a dump version of Doug's answer :)

Here's a fast solution in C using bit twiddling to find min(x, y). It is a modified version of #Doug Currie's answer and inspired by the answer to the Find the Minimum Positive Value question:
bool lowestPositive(int a, int b, int* pout)
{
/* exclude zero, make a negative number to be larger any positive number */
unsigned x = (a - 1), y = (b - 1);
/* min(x, y) + 1 */
*pout = y + ((x - y) & -(x < y)) + 1;
return *pout > 0;
}
Example:
/** gcc -std=c99 *.c && a */
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdbool.h>
void T(int a, int b)
{
int result = 0;
printf("%d %d ", a, b);
if (lowestPositive(a, b, &result))
printf(": %d\n", result);
else
printf(" are not positive\n");
}
int main(int argc, char *argv[])
{
T(5, 6);
T(6, 5);
T(6, -1);
T(-1, -2);
T(INT_MIN, INT_MAX);
T(INT_MIN, INT_MIN);
T(INT_MAX, INT_MIN);
T(0, -1);
T(0, INT_MIN);
T(-1, 0);
T(INT_MIN, 0);
T(INT_MAX, 0);
T(0, INT_MAX);
T(0, 0);
return 0;
}
Output:
5 6 : 5
6 5 : 5
6 -1 : 6
-1 -2 are not positive
-2147483648 2147483647 : 2147483647
-2147483648 -2147483648 are not positive
2147483647 -2147483648 : 2147483647
0 -1 are not positive
0 -2147483648 are not positive
-1 0 are not positive
-2147483648 0 are not positive
2147483647 0 : 2147483647
0 2147483647 : 2147483647
0 0 are not positive

This will handle all possible inputs as you request.
bool lowestPositive(int a, int b, int& result)
{
if ( a < 0 and b < 0 )
return false
result = std::min<unsigned int>( a, b );
return true;
}
That being said, the signature you supply allows sneaky bugs to appear, as it is easy to ignore the return value of this function or not even remember that there is a return value that has to be checked to know if the result is correct.
You may prefer one of these alternatives that makes it harder to overlook that a success result has to be checked:
boost::optional<int> lowestPositive(int a, int b)
{
boost::optional<int> result;
if ( a >= 0 or b >= 0 )
result = std::min<unsigned int>( a, b );
return result;
}
or
void lowestPositive(int a, int b, int& result, bool &success)
{
success = ( a >= 0 or b >= 0 )
if ( success )
result = std::min<unsigned int>( a, b );
}

tons of the answers here are ignoring the fact that zero isn't positive :)
with tricky casting and tern:
bool leastPositive(int a, int b, int& result) {
result = ((unsigned) a < (unsigned) b) ? a : b;
return result > 0;
}
less cute:
bool leastPositive(int a, int b, int& result) {
if(a > 0 && b > 0)
result = a < b ? a : b;
else
result = a > b ? a : b:
return result > 0;
}

I suggest you refactor the function into simpler functions. Furthermore, this allows your compiler to better enforce expected input data.
unsigned int minUnsigned( unsigned int a, unsigned int b )
{
return ( a < b ) ? a : b;
}
bool lowestPositive( int a, int b, int& result )
{
if ( a < 0 && b < 0 ) // SO comments refer to the previous version that had || here
{
return false;
}
result = minUnsigned( (unsigned)a, (unsigned)b ); // negative signed integers become large unsigned values
return true;
}
This works on all three signed-integer representations allowed by ISO C:
two's complement, one's complement, and even sign/magnitude. All we care about is that any positive signed integer (MSB cleared) compares below anything with the MSB set.
This actually compiles to really nice code with clang for x86, as you can see on the Godbolt Compiler Explorer. gcc 5.3 unfortunately does a much worse job.

Hack using "magic constant" -1:
enum
{
INVALID_POSITIVE = -1
};
int lowestPositive(int a, int b)
{
return (a>=0 ? ( b>=0 ? (b > a ? a : b ) : INVALID_POSITIVE ) : INVALID_POSITIVE );
}
This makes no assumptions about the numbers being positive.

Pseudocode because I have no compiler on hand:
////0 if both negative, 1 if u0 positive, 2 if u1 positive, 3 if both positive
switch((u0 > 0 ? 1 : 0) + (u1 > 0 ? 2 : 0)) {
case 0:
return false; //Note that this leaves the result value undef.
case 1:
result = u0;
return true;
case 2:
result = u1;
return true;
case 3:
result = (u0 < u1 ? u0 : u1);
return true;
default: //undefined and probably impossible condition
return false;
}
This is compact without a lot of if statements, but relies on the ternary " ? : " operator, which is just a compact if, then, else statement. "(true ? "yes" : "no")" returns "yes", "(false ? "yes" : "no") returns "no".
In a normal switch statement after every case you should have a break;, to exit the switch. In this case we have a return statement, so we're exiting the entire function.

With all due respect, your problem may be that the English phrase used to describe the problem really does hide some complexity (or at least some unresolved questions). In my experience, this is a common source of bugs and/or unfulfilled expectations in the "real world" as well. Here are some of the issues I observed:
Some programmers use a naming
convention in which a leading u
implies unsigned, but you didn't
state explicitly whether your
"numbers" are unsigned or signed
(or, for that matter, whether they
are even supposed to be integral!)
I suspect that all of us who read it
assumed that if one argument is
positive and the other is not, then
the (only) positive argument value
is the correct response, but that is
not explicitly stated.
The description also doesn't define
the required behavior if both values
are non-positive.
Finally, some of the responses
offered prior to this post seem to
imply that the responder thought
(mistakenly) that 0 is positive! A
more specific requirements statement
might help prevent any
misunderstanding (or make it clear
that the issue of zero hadn't been
thought out completely when the
requirement was written).
I'm not trying to be overly critical; I'm just suggesting that a more precisely-written requirement will probably help, and will probably also make it clear whether some of the complexity you're concerned about in the implementation is really implicit in the nature of the problem.

Three lines with the use (abuse?) of the ternary operator
int *smallest_positive(int *u1, int *u2) {
if (*u1 < 0) return *u2 >= 0 ? u2 : NULL;
if (*u2 < 0) return u1;
return *u1 < *u2 ? u1 : u2;
}
Don't know about efficiency or what to do if both u1 and u2 are negative. I opted to return NULL (which has to be checked in the caller); a return of a pointer to a static -1 might be more useful.
Edited to reflect the changes in the original question :)
bool smallest_positive(int u1, int u2, int& result) {
if (u1 < 0) {
if (u2 < 0) return false; /* result unchanged */
result = u2;
} else {
if (u2 < 0) result = u1;
else result = u1 < u2 ? u1 : u2;
}
return true;
}

uint lowestPos(uint a, uint b) { return (a < b ? a : b); }
You are looking for the smallest positive, it is be wise to accept positive values only in that case. You don't have to catch the negative values problem in your function, you should solve it at an earlier point in the caller function. For the same reason I left the boolean oit.
A precondition is that they are not equal, you would use it like this in that way:
if (a == b)
cout << "equal";
else
{
uint lowest = lowestPos(a, b);
cout << (lowest == a ? "a is lowest" : "b is lowest");
}
You can introduce const when you want to prevent changes or references if you want to change the result. Under normal conditions the computer will optimize and even inline the function.

No cleverness, reasonable clarity, works for ints and floats:
template<class T>
inline
bool LowestPositive( const T a, const T b, T* result ) {
const bool b_is_pos = b > 0;
if( a > 0 && ( !b_is_pos || a < b ) ) {
*result = a;
return true;
}
if( b_is_pos ) {
*result = b;
return true;
}
return false;
}
Note that 0 (zero) is not a positive number.
OP asks for dealing with numbers (I interpret this as ints and floats).
Only dereference result pointer if there is a positive result (performance)
Only test a and b for positiveness once (performance -- not sure if such a test is expensive?)
Note also that the accepted answer (by tvanfosson) is wrong. It fails if a is positive and b is negative (saying that "neither is positive"). (This is the only reason I add a separate answer -- I don't have reputation enough to add comments.)

My idea is based on using min and max. And categorized the result into three cases, where
min <= 0 and max <= 0
min <= 0 and max > 0
min > 0 and max > 0
The best thing is that it's not look too complicated.
Code:
bool lowestPositive(int a, int b, int& result)
{
int min = (a < b) ? a : b;
int max = (a > b) ? a : b;
bool smin = min > 0;
bool smax = max > 0;
if(!smax) return false;
if(smin) result = min;
else result = max;
return true;
}

After my first post was rejected, allow me to suggest that you are prematurely optimizing the problem and you shouldn't worry about having lots of if statements. The code you're writing naturally requires multiple 'if' statements, and whether they are expressed with the ternary if operator (A ? B : C) or classic if blocks, the execution time is the same, the compiler is going to optimize almost all of the code posted into very nearly the same logic.
Concern yourself with the readability and reliability of your code rather than trying to outwit your future self or anyone else who reads the code. Every solution posted is O(1) from what I can tell, that is, every single solution will contribute insignificantly to the performance of your code.
I would like to suggest that this post be tagged "premature optimization," the poster is not looking for elegant code.

Related

Efficient/portable signed integer mod positive integer returning nonnegative?

In C and C++, I want to divide and mod a signed integer by a positive integer such that the div rounds towards negative infinity and the mod always returns nonnegative.
For the division I have:
int64_t SignedDiv(int64_t A_signed, int64_t B_positive) {
return A_signed / B_positive - (A_signed % B_positive < 0);
}
which is taken from this answer to a similar question.
For the mod I have:
int64_t SignedMod(int64_t A_signed, int64_t B_positive) {
return A_signed - B_positive * SignedDiv(A_signed, B_positive);
}
which seems terrible. Is there a way to rewrite SignedMod such that it will return the same thing (and is equally portable) but is more efficient?
Here is the compilation output on godbolt:
https://godbolt.org/z/eeG93xh5f
This saves 2 opcodes on x86_64 with clang -O3:
int64_t SignedMod2(int64_t A_signed, int64_t B_positive) {
int64_t t = A_signed % B_positive;
if (t < 0) t += B_positive;
return t;
}
Using gcc or clang -Os eliminates all the jumps in the output which is probably a fair bit faster. I have no idea what clang is doing there blowing up the code length with needless jumps.
mod always returns nonnegative.
Pulled from this answer: What's the difference between “mod” and “remainder”?. Also handles b < 0 corner cases - even though OP says b > 0.
int modulo_Euclidean2(int a, int b) {
if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
Like #Goswin von Brederlow when b > 0.

Can we and how safe is to "signed" to "unsigned" trick to save one comparison in this case?

For example
bool CheckWithinBoundary(int x, int b) {
return (x>=0) && (x <= b);
}
bool CheckWithinBoundary2(int x, int b) {
return static_cast<uint32>(x) <= static_cast<uint32>(b);
}
CheckWithinBoundary2 can save one comparison.
My question is:
Can today's compiler optimize code using this? Or how can I make the
compiler do this kind of optimization?
Is there any danger to use this trick?
The answer to 2 is, yes, there is, these two are not the same. It seems that you are silently assuming that b >= 0, too. Consider e.g x == 1 and b == -1, this would give false for the first case and true for the second.
(I switch to C notation, this is easier to me, and since you also seem to be interested in it)
So we have that in fact
static_assert(INT_MAX < UINT_MAX);
bool CheckWithinBoundary(int x, int b) {
return (b >=0) && (x>=0) && (x <= b);
}
bool CheckWithinBoundary2(unsigned x, unsigned b) {
return (b >=0) && (x <= b);
}
if it compiles, are equivalent on all architectures where INT_MAX < UINT_MAX, and then the implicit conversion int --> unsigned does the right thing.
But be careful, you note that I use unsigned and not uint32_t, because you have to be sure to use an unsigned type with the same width. I don't know if there are architectures with 64 bit int, but there your method would fail.

Find out (in C++) if binary number is prefix of another

I need a function with a header like this:
bool is_prefix(int a, int b, int* c) {
// ...
}
If a is, read as a binary number string, a prefix of b, then set *c to be the rest of b (i.e. "what b has more than a") and return true. Otherwise, return false. Assume that binary strings always start with "1".
Of course - it is easy to do by comparing bit by bit (leftshift b until b==a). But is there a solution which is more efficient, without iterating over the bits?
Example: a=100 (4), b=1001 (9). Now set *c to 1.
You can use your favorite "fast" method to find the highest set bit. Let's call the function msb().
bool is_prefix (int a, int b, int *c) {
if (a == 0 || b == 0 || c == 0) return false;
int d = msb(b) - msb(a);
if (d < 0) return false;
if ((b >> d) == a) {
*c = b ^ (a << d);
return true;
}
return false;
}
Shift b so its high order bit aligns with a, and compare that with a. If they are equal, then a is a "prefix" of b.
This algorithm's performance depends on the performance of msb(). If it is constant, then this algorithm is constant. If msb() is expensive, then the "easy approach" may be the fastest approach.
I'm not too sure, but would something like the following work:
bool
is_prefix( unsigned a, unsigned b, unsigned* c )
{
unsigned mask = -1;
while ( mask != 0 && a != (b & mask) ) {
a <<= 1;
mask <<= 1;
}
c = b & ~mask;
return mask != 0;
}
(Just off the top of my head, so there could be errors.)

Detecting a negative 0 stored as a double in C++

I am doing some mathematical calculations (trying to convert Matlab code into C++, using VS2010) and I need to be able to tell if at some point I get a negative 0.
According to the IEEE standard -0/+0 differ only in the sign bit (the rest are 0).
I have used the following piece of code (post) to interpret my double as a unsigned char
double f = -5;
unsigned char *c = reinterpret_cast<unsigned char *>(&f);
for(int i=(sizeof(double)-1); i>=0; i--){
printf("%02X", c[i]);
}
Trying it with 5/-5 I get the expected result:
C014000000000000 (-5)
4014000000000000 (5)
But when I try it with 0/-0 I get only zeros in both case. VS2010 states that they are IEEE compliant (msdn) so I'm not sure which part of it I'm not getting.
If 0/-0 are indeed stored in the memory in the exact same way, there is no way I can tell them apart if I need to so I should stop wasting my time :) Right?
If you write
double d = -0;
the following will happen:
First, -0 will be evaluated, which is of type int, because 0 is of type int. The result will be 0. Then 0 will be converted to double and assigned thus being +0.0, and not -0.0
double d = -0.0; // is your solution.
In addition to Armen's good answer, you should use signbit to detect this. Doing so will protect you from endian issues:
#include <iostream>
#include <cmath>
int main()
{
std::cout << std::signbit(0.0) << '\n';
std::cout << std::signbit(-0.0) << '\n';
}
0
1
Same kind of function rewritten into shorter form:
static inline unsigned bool signbit(double& d)
{
return ( ((unsigned char*)&d)[sizeof(double)-1] & 0x80) != 0;
}
int EstimateDoubleBufferSize( double& d )
{
int len = 0;
if( signbit(d) ) //if ( d < 0 )
{
d = -d;
len++;
}
d += 0.0000005;
int m = (int) log10(d);
if( m < 0 )
m = 1; // 0.xxxx - include 0
else
m++; // Include first character
len += m + 1 /*dot*/ + 6 /* precision after . */;
return len;
}
Also I needed to figure out microsoft c++ compiler sprintf size - included function for that as well.

Rounding up to the nearest multiple of a number

OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.
Is this the correct way to round up to a multiple of a number in C++?
I know there are other questions related to this but I am specficially interested to know what is the best way to do this in C++:
int roundUp(int numToRound, int multiple)
{
if(multiple == 0)
{
return numToRound;
}
int roundDown = ( (int) (numToRound) / multiple) * multiple;
int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc);
}
Update:
Sorry I probably didn't make intention clear. Here are some examples:
roundUp(7, 100)
//return 100
roundUp(117, 100)
//return 200
roundUp(477, 100)
//return 500
roundUp(1077, 100)
//return 1100
roundUp(52, 20)
//return 60
roundUp(74, 30)
//return 90
This works for positive numbers, not sure about negative. It only uses integer math.
int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = numToRound % multiple;
if (remainder == 0)
return numToRound;
return numToRound + multiple - remainder;
}
Edit: Here's a version that works with negative numbers, if by "up" you mean a result that's always >= the input.
int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = abs(numToRound) % multiple;
if (remainder == 0)
return numToRound;
if (numToRound < 0)
return -(abs(numToRound) - remainder);
else
return numToRound + multiple - remainder;
}
Without conditions:
int roundUp(int numToRound, int multiple)
{
assert(multiple);
return ((numToRound + multiple - 1) / multiple) * multiple;
}
This works like rounding away from zero for negative numbers
Version that works also for negative numbers:
int roundUp(int numToRound, int multiple)
{
assert(multiple);
int isPositive = (int)(numToRound >= 0);
return ((numToRound + isPositive * (multiple - 1)) / multiple) * multiple;
}
Tests
If multiple is a power of 2 (faster in ~3.7 times)
int roundUp(int numToRound, int multiple)
{
assert(multiple && ((multiple & (multiple - 1)) == 0));
return (numToRound + multiple - 1) & -multiple;
}
Tests
This works when factor will always be positive:
int round_up(int num, int factor)
{
return num + factor - 1 - (num + factor - 1) % factor;
}
Edit: This returns round_up(0,100)=100. Please see Paul's comment below for a solution that returns round_up(0,100)=0.
This is a generalization of the problem of "how do I find out how many bytes n bits will take? (A: (n bits + 7) / 8).
int RoundUp(int n, int roundTo)
{
// fails on negative? What does that mean?
if (roundTo == 0) return 0;
return ((n + roundTo - 1) / roundTo) * roundTo; // edit - fixed error
}
int roundUp(int numToRound, int multiple)
{
if(multiple == 0)
{
return 0;
}
return ((numToRound - 1) / multiple + 1) * multiple;
}
And no need to mess around with conditions
This is the modern c++ approach using a template function which is working for float, double, long, int and short (but not for long long, and long double because of the used double values).
#include <cmath>
#include <iostream>
template<typename T>
T roundMultiple( T value, T multiple )
{
if (multiple == 0) return value;
return static_cast<T>(std::round(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}
int main()
{
std::cout << roundMultiple(39298.0, 100.0) << std::endl;
std::cout << roundMultiple(20930.0f, 1000.0f) << std::endl;
std::cout << roundMultiple(287399, 10) << std::endl;
}
But you can easily add support for long long and long double with template specialisation as shown below:
template<>
long double roundMultiple<long double>( long double value, long double multiple)
{
if (multiple == 0.0l) return value;
return std::round(value/multiple)*multiple;
}
template<>
long long roundMultiple<long long>( long long value, long long multiple)
{
if (multiple == 0.0l) return value;
return static_cast<long long>(std::round(static_cast<long double>(value)/static_cast<long double>(multiple))*static_cast<long double>(multiple));
}
To create functions to round up, use std::ceil and to always round down use std::floor. My example from above is rounding using std::round.
Create the "round up" or better known as "round ceiling" template function as shown below:
template<typename T>
T roundCeilMultiple( T value, T multiple )
{
if (multiple == 0) return value;
return static_cast<T>(std::ceil(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}
Create the "round down" or better known as "round floor" template function as shown below:
template<typename T>
T roundFloorMultiple( T value, T multiple )
{
if (multiple == 0) return value;
return static_cast<T>(std::floor(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}
For anyone looking for a short and sweet answer. This is what I used. No accounting for negatives.
n - (n % r)
That will return the previous factor.
(n + r) - (n % r)
Will return the next. Hope this helps someone. :)
float roundUp(float number, float fixedBase) {
if (fixedBase != 0 && number != 0) {
float sign = number > 0 ? 1 : -1;
number *= sign;
number /= fixedBase;
int fixedPoint = (int) ceil(number);
number = fixedPoint * fixedBase;
number *= sign;
}
return number;
}
This works for any float number or base (e.g. you can round -4 to the nearest 6.75). In essence it is converting to fixed point, rounding there, then converting back. It handles negatives by rounding AWAY from 0. It also handles a negative round to value by essentially turning the function into roundDown.
An int specific version looks like:
int roundUp(int number, int fixedBase) {
if (fixedBase != 0 && number != 0) {
int sign = number > 0 ? 1 : -1;
int baseSign = fixedBase > 0 ? 1 : 0;
number *= sign;
int fixedPoint = (number + baseSign * (fixedBase - 1)) / fixedBase;
number = fixedPoint * fixedBase;
number *= sign;
}
return number;
}
Which is more or less plinth's answer, with the added negative input support.
First off, your error condition (multiple == 0) should probably have a return value. What? I don't know. Maybe you want to throw an exception, that's up to you. But, returning nothing is dangerous.
Second, you should check that numToRound isn't already a multiple. Otherwise, when you add multiple to roundDown, you'll get the wrong answer.
Thirdly, your casts are wrong. You cast numToRound to an integer, but it's already an integer. You need to cast to to double before the division, and back to int after the multiplication.
Lastly, what do you want for negative numbers? Rounding "up" can mean rounding to zero (rounding in the same direction as positive numbers), or away from zero (a "larger" negative number). Or, maybe you don't care.
Here's a version with the first three fixes, but I don't deal with the negative issue:
int roundUp(int numToRound, int multiple)
{
if(multiple == 0)
{
return 0;
}
else if(numToRound % multiple == 0)
{
return numToRound
}
int roundDown = (int) (( (double) numToRound / multiple ) * multiple);
int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc);
}
Round to Power of Two:
Just in case anyone needs a solution for positive numbers rounded to the nearest multiple of a power of two (because that's how I ended up here):
// number: the number to be rounded (ex: 5, 123, 98345, etc.)
// pow2: the power to be rounded to (ex: to round to 16, use '4')
int roundPow2 (int number, int pow2) {
pow2--; // because (2 exp x) == (1 << (x -1))
pow2 = 0x01 << pow2;
pow2--; // because for any
//
// (x = 2 exp x)
//
// subtracting one will
// yield a field of ones
// which we can use in a
// bitwise OR
number--; // yield a similar field for
// bitwise OR
number = number | pow2;
number++; // restore value by adding one back
return number;
}
The input number will stay the same if it is already a multiple.
Here is the x86_64 output that GCC gives with -O2 or -Os (9Sep2013 Build - godbolt GCC online):
roundPow2(int, int):
lea ecx, [rsi-1]
mov eax, 1
sub edi, 1
sal eax, cl
sub eax, 1
or eax, edi
add eax, 1
ret
Each C line of code corresponds perfectly with its line in the assembly: http://goo.gl/DZigfX
Each of those instructions are extremely fast, so the function is extremely fast too. Since the code is so small and quick, it might be useful to inline the function when using it.
Credit:
Algorithm: Hagen von Eitzen # Math.SE
Godbolt Interactive Compiler: #mattgodbolt/gcc-explorer on GitHub
I'm using:
template <class _Ty>
inline _Ty n_Align_Up(_Ty n_x, _Ty n_alignment)
{
assert(n_alignment > 0);
//n_x += (n_x >= 0)? n_alignment - 1 : 1 - n_alignment; // causes to round away from zero (greatest absolute value)
n_x += (n_x >= 0)? n_alignment - 1 : -1; // causes to round up (towards positive infinity)
//n_x += (_Ty(-(n_x >= 0)) & n_alignment) - 1; // the same as above, avoids branch and integer multiplication
//n_x += n_alignment - 1; // only works for positive numbers (fastest)
return n_x - n_x % n_alignment; // rounds negative towards zero
}
and for powers of two:
template <class _Ty>
bool b_Is_POT(_Ty n_x)
{
return !(n_x & (n_x - 1));
}
template <class _Ty>
inline _Ty n_Align_Up_POT(_Ty n_x, _Ty n_pot_alignment)
{
assert(n_pot_alignment > 0);
assert(b_Is_POT(n_pot_alignment)); // alignment must be power of two
-- n_pot_alignment;
return (n_x + n_pot_alignment) & ~n_pot_alignment; // rounds towards positive infinity (i.e. negative towards zero)
}
Note that both of those round negative values towards zero (that means round to positive infinity for all values), neither of them relies on signed overflow (which is undefined in C/C++).
This gives:
n_Align_Up(10, 100) = 100
n_Align_Up(110, 100) = 200
n_Align_Up(0, 100) = 0
n_Align_Up(-10, 100) = 0
n_Align_Up(-110, 100) = -100
n_Align_Up(-210, 100) = -200
n_Align_Up_POT(10, 128) = 128
n_Align_Up_POT(130, 128) = 256
n_Align_Up_POT(0, 128) = 0
n_Align_Up_POT(-10, 128) = 0
n_Align_Up_POT(-130, 128) = -128
n_Align_Up_POT(-260, 128) = -256
Round to nearest multiple that happens to be a power of 2
unsigned int round(unsigned int value, unsigned int multiple){
return ((value-1u) & ~(multiple-1u)) + multiple;
}
This can be useful for when allocating along cachelines, where the rounding increment you want is a power of two, but the resulting value only needs to be a multiple of it. On gcc the body of this function generates 8 assembly instructions with no division or branches.
round( 0, 16) -> 0
round( 1, 16) -> 16
round( 16, 16) -> 16
round(257, 128) -> 384 (128 * 3)
round(333, 2) -> 334
Probably safer to cast to floats and use ceil() - unless you know that the int division is going to produce the correct result.
int noOfMultiples = int((numToRound / multiple)+0.5);
return noOfMultiples*multiple
C++ rounds each number down,so if you add 0.5 (if its 1.5 it will be 2) but 1.49 will be 1.99 therefore 1.
EDIT - Sorry didn't see you wanted to round up, i would suggest using a ceil() method instead of the +0.5
well for one thing, since i dont really understand what you want to do, the lines
int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc);
could definitely be shortened to
int roundUp = roundDown + multiple;
return roundUp;
may be this can help:
int RoundUpToNearestMultOfNumber(int val, int num)
{
assert(0 != num);
return (floor((val + num) / num) * num);
}
To always round up
int alwaysRoundUp(int n, int multiple)
{
if (n % multiple != 0) {
n = ((n + multiple) / multiple) * multiple;
// Another way
//n = n - n % multiple + multiple;
}
return n;
}
alwaysRoundUp(1, 10) -> 10
alwaysRoundUp(5, 10) -> 10
alwaysRoundUp(10, 10) -> 10
To always round down
int alwaysRoundDown(int n, int multiple)
{
n = (n / multiple) * multiple;
return n;
}
alwaysRoundDown(1, 10) -> 0
alwaysRoundDown(5, 10) -> 0
alwaysRoundDown(10, 10) -> 10
To round the normal way
int normalRound(int n, int multiple)
{
n = ((n + multiple/2)/multiple) * multiple;
return n;
}
normalRound(1, 10) -> 0
normalRound(5, 10) -> 10
normalRound(10, 10) -> 10
I found an algorithm which is somewhat similar to one posted above:
int[(|x|+n-1)/n]*[(nx)/|x|], where x is a user-input value and n is the multiple being used.
It works for all values x, where x is an integer (positive or negative, including zero). I wrote it specifically for a C++ program, but this can basically be implemented in any language.
For negative numToRound:
It should be really easy to do this but the standard modulo % operator doesn't handle negative numbers like one might expect. For instance -14 % 12 = -2 and not 10. First thing to do is to get modulo operator that never returns negative numbers. Then roundUp is really simple.
public static int mod(int x, int n)
{
return ((x % n) + n) % n;
}
public static int roundUp(int numToRound, int multiple)
{
return numRound + mod(-numToRound, multiple);
}
This is what I would do:
#include <cmath>
int roundUp(int numToRound, int multiple)
{
// if our number is zero, return immediately
if (numToRound == 0)
return multiple;
// if multiplier is zero, return immediately
if (multiple == 0)
return numToRound;
// how many times are number greater than multiple
float rounds = static_cast<float>(numToRound) / static_cast<float>(multiple);
// determine, whether if number is multiplier of multiple
int floorRounds = static_cast<int>(floor(rounds));
if (rounds - floorRounds > 0)
// multiple is not multiplier of number -> advance to the next multiplier
return (floorRounds+1) * multiple;
else
// multiple is multiplier of number -> return actual multiplier
return (floorRounds) * multiple;
}
The code might not be optimal, but I prefer clean code than dry performance.
int roundUp (int numToRound, int multiple)
{
return multiple * ((numToRound + multiple - 1) / multiple);
}
although:
won't work for negative numbers
won't work if numRound + multiple overflows
would suggest using unsigned integers instead, which has defined overflow behaviour.
You'll get an exception is multiple == 0, but it isn't a well-defined problem in that case anyway.
c:
int roundUp(int numToRound, int multiple)
{
return (multiple ? (((numToRound+multiple-1) / multiple) * multiple) : numToRound);
}
and for your ~/.bashrc:
roundup()
{
echo $(( ${2} ? ((${1}+${2}-1)/${2})*${2} : ${1} ))
}
I use a combination of modulus to nullify the addition of the remainder if x is already a multiple:
int round_up(int x, int div)
{
return x + (div - x % div) % div;
}
We find the inverse of the remainder then modulus that with the divisor again to nullify it if it is the divisor itself then add x.
round_up(19, 3) = 21
Here's my solution based on the OP's suggestion, and the examples given by everyone else. Since most everyone was looking for it to handle negative numbers, this solution does just that, without the use of any special functions, i.e. abs, and the like.
By avoiding the modulus and using division instead, the negative number is a natural result, although it's rounded down. After the rounded down version is calculated, then it does the required math to round up, either in the negative or positive direction.
Also note that no special functions are used to calculate anything, so there is a small speed boost there.
int RoundUp(int n, int multiple)
{
// prevent divide by 0 by returning n
if (multiple == 0) return n;
// calculate the rounded down version
int roundedDown = n / multiple * multiple;
// if the rounded version and original are the same, then return the original
if (roundedDown == n) return n;
// handle negative number and round up according to the sign
// NOTE: if n is < 0 then subtract the multiple, otherwise add it
return (n < 0) ? roundedDown - multiple : roundedDown + multiple;
}
I think this should help you. I have written the below program in C.
# include <stdio.h>
int main()
{
int i, j;
printf("\nEnter Two Integers i and j...");
scanf("%d %d", &i, &j);
int Round_Off=i+j-i%j;
printf("The Rounded Off Integer Is...%d\n", Round_Off);
return 0;
}
Endless possibilities, for signed integers only:
n + ((r - n) % r)
/// Rounding up 'n' to the nearest multiple of number 'b'.
/// - Not tested for negative numbers.
/// \see http://stackoverflow.com/questions/3407012/
#define roundUp(n,b) ( (b)==0 ? (n) : ( ((n)+(b)-1) - (((n)-1)%(b)) ) )
/// \c test->roundUp().
void test_roundUp() {
// yes_roundUp(n,b) ( (b)==0 ? (n) : ( (n)%(b)==0 ? n : (n)+(b)-(n)%(b) ) )
// yes_roundUp(n,b) ( (b)==0 ? (n) : ( ((n + b - 1) / b) * b ) )
// no_roundUp(n,b) ( (n)%(b)==0 ? n : (b)*( (n)/(b) )+(b) )
// no_roundUp(n,b) ( (n)+(b) - (n)%(b) )
if (true) // couldn't make it work without (?:)
{{ // test::roundUp()
unsigned m;
{ m = roundUp(17,8); } ++m;
assertTrue( 24 == roundUp(17,8) );
{ m = roundUp(24,8); }
assertTrue( 24 == roundUp(24,8) );
assertTrue( 24 == roundUp(24,4) );
assertTrue( 24 == roundUp(23,4) );
{ m = roundUp(23,4); }
assertTrue( 24 == roundUp(21,4) );
assertTrue( 20 == roundUp(20,4) );
assertTrue( 20 == roundUp(19,4) );
assertTrue( 20 == roundUp(18,4) );
assertTrue( 20 == roundUp(17,4) );
assertTrue( 17 == roundUp(17,0) );
assertTrue( 20 == roundUp(20,0) );
}}
}
This is getting the results you are seeking for positive integers:
#include <iostream>
using namespace std;
int roundUp(int numToRound, int multiple);
int main() {
cout << "answer is: " << roundUp(7, 100) << endl;
cout << "answer is: " << roundUp(117, 100) << endl;
cout << "answer is: " << roundUp(477, 100) << endl;
cout << "answer is: " << roundUp(1077, 100) << endl;
cout << "answer is: " << roundUp(52,20) << endl;
cout << "answer is: " << roundUp(74,30) << endl;
return 0;
}
int roundUp(int numToRound, int multiple) {
if (multiple == 0) {
return 0;
}
int result = (int) (numToRound / multiple) * multiple;
if (numToRound % multiple) {
result += multiple;
}
return result;
}
And here are the outputs:
answer is: 100
answer is: 200
answer is: 500
answer is: 1100
answer is: 60
answer is: 90
I think this works:
int roundUp(int numToRound, int multiple) {
return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;
}
The accepted answer doesn't work very well, I thought I'd try my hand at this problem, this should round up all integers you throw at it:
int round_up(int input, unsigned int multiple) {
if (input < 0) { return input - input % multiple; }
return input + multiple - (((input - 1) % multiple) + 1);
}
If the number is negative it's easy, take the remainder and add it onto the input, that'll do the trick.
If the number is not negative, you have to subtract the remainder from the multiple and add that to round up. The problem with that is that if input is exactly on a multiple, it will still get rounded up to the next multiple because multiple - 0 = multiple.
To remedy this we do a cool little hack: subtract one from input before doing the remainder, then add it back on to the resulting remainder. This doesn't affect anything at all unless input is on a multiple. In that case, subtracting one will cause the remainder to the previous multiple to be calculated. After adding one again, you'll have exactly the multiple. Obviously subtracting this from itself yields 0, so your input value doesn't change.