How to calculate -1 modulo 1000000007 in C++ - c++

I tried to get the result of -1 modulo 1000000007 using the % operator of C++
and fmod function.
The output is -1, but -1 modulo 1000000007==1000000006.
What have I done wrong?

Plainly said, you took the wrong operator.
C++ and C % is not modulo, but remainder.
assert(a / b * b + a % b == a); // for integral types
If a is non-negative, modulo and remainder are the same.
Otherwise the return-value is negative, just add b.
template<class T>
inline constexpr auto
modulo(T a, T b) -> decltype(a%b) {
auto r = a % b;
if (r < 0) r += b;
return r;
}
Or (also) for C:
#define modulo(a, b) (a % b < 0 ? a % b + b : a % b)
For completeness: Before C++11, a / b could always round down instead of always to 0, though C++03 already had a note that the next standard would probably mandate rounding to 0.
See Wikipedia on modulo:
Modulo is the remainder of euclidiean division, and always in range 0 <= modulo < divisor
And on remainder:
In mathematics, the remainder is the amount "left over" after performing some computation.

Modulo function that handles negative divisors as well as positive divisors:
template<class T>
inline constexpr auto
modulo(T a, T b) -> decltype(a%b) {
auto r = a % b;
if((b > 0 && r < 0) || (b < 0 && r > 0))
r += b;
return r;
}

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.

How to modulo this formula?

I would like to write this formula in C++ language:
(2<=n<=1e5), (1<=k<=n), (2<=M<=1e9).
I would like to do this without using special structures.
Unfortunately in this formula there are a lot of cases which effectively make modulation difficult. Example: ((n-k)!) mod M can be equal to 0, or ((n-1)(n-2))/4 may not be an integer. I will be very grateful for any help.
(n−1)!/(n−k)! can be handled by computing the product (n−k+1)…(n−1).
(n−1)! (n−1)(n−2)/4 can be handled by handling n ≤ 2 (0) and n ≥ 3
(3…(n−1) (n−1)(n−2)/2) separately.
Untested C++:
#include <cassert>
#include <cstdint>
class Residue {
public:
// Accept int64_t for convenience.
explicit Residue(int64_t rep, int32_t modulus) : modulus_(modulus) {
assert(modulus > 0);
rep_ = rep % modulus;
if (rep_ < 0)
rep_ += modulus;
}
// Return int64_t for convenience.
int64_t rep() const { return rep_; }
int32_t modulus() const { return modulus_; }
private:
int32_t rep_;
int32_t modulus_;
};
Residue operator+(Residue a, Residue b) {
assert(a.modulus() == b.modulus());
return Residue(a.rep() + b.rep(), a.modulus());
}
Residue operator-(Residue a, Residue b) {
assert(a.modulus() == b.modulus());
return Residue(a.rep() - b.rep(), a.modulus());
}
Residue operator*(Residue a, Residue b) {
assert(a.modulus() == b.modulus());
return Residue(a.rep() * b.rep(), a.modulus());
}
Residue QuotientOfFactorialsMod(int32_t a, int32_t b, int32_t modulus) {
assert(modulus > 0);
assert(b >= 0);
assert(a >= b);
Residue result(1, modulus);
// Don't initialize with b + 1 because it could overflow.
for (int32_t i = b; i < a; i++) {
result = result * Residue(i + 1, modulus);
}
return result;
}
Residue FactorialMod(int32_t a, int32_t modulus) {
assert(modulus > 0);
assert(a >= 0);
return QuotientOfFactorialsMod(a, 0, modulus);
}
Residue Triangular(int32_t a, int32_t modulus) {
assert(modulus > 0);
return Residue((static_cast<int64_t>(a) + 1) * a / 2, modulus);
}
Residue F(int32_t n, int32_t k, int32_t m) {
assert(n >= 2);
assert(n <= 100000);
assert(k >= 1);
assert(k <= n);
assert(m >= 2);
assert(m <= 1000000000);
Residue n_res(n, m);
Residue n_minus_1(n - 1, m);
Residue n_minus_2(n - 2, m);
Residue k_res(k, m);
Residue q = QuotientOfFactorialsMod(n - 1, n - k, m);
return q * (k_res - n_res) * n_minus_1 +
(FactorialMod(n - 1, m) - q) * k_res * n_minus_1 +
(n > 2 ? QuotientOfFactorialsMod(n - 1, 2, m) *
(n_res * n_minus_1 + Triangular(n - 2, m))
: Residue(1, m));
}
As mentioned in the other answer dividing factorials can be evaluated directly without division. Also you need 64bit arithmetics in order to store your subresults. And use modulo after each multiplication otherwise you would need very huge numbers which would take forever to compute.
Also you mention ((n-1)(n-2))/4 can be non just integer how to deal with that is questionable as we do not have any context to what you are doing. However you can move /2 before brackets (apply it on (n-1)! so modpi without 2 beware not to divide the already modded factorial!!!) and then you have no remainder as the (n-1)*(n-2)/4 become (n-1)*(n-2)/2 and the (n-1)*(n-2) is always odd (divisible by 2). The only "problem" is when n=2 as the n*(n-1)/2 is 1 but the /2 moved before bracket will round down the (n-1)! so you should handle it as special case by not moving the /2 before brackets (not included in code below).
I see it like this:
typedef unsigned __int64 u64;
u64 modpi(u64 x0,u64 x1,u64 p) // ( x0*(x0+1)*(x0+2)*...*x1 ) mod p
{
u64 x,y;
if (x0>x1){ x=x0; x0=x1; x1=x; }
for (y=1,x=x0;x<=x1;x++){ y*=x; y%=p; }
return y;
}
void main()
{
u64 n=100,k=20,m=123456789,a,b,b2,c,y;
a =modpi(n-k+1,n-1,m); // (n-1)!/(n-k)!
b =modpi(1,n-1,m); // (n-1)! mod m
b2=modpi(3,n-1,m); // (n-1)!/2 mod m
c =((n*(n-1)))%m; // 2*( n*(n-1)/2 + (n-1)*(n-2)/4 ) mod m
c+=(((n-1)*(n-2))/2)%m;
y =(((a*(k-n))%m)*(n-1))%m; // ((n-1)!/(n-k)!)*(k-1)*(n-1) mod m
y+=b; // (n-1)! mod m
y-=(((a*k)%m)*(n-1))%m; // ((n-1)!/(n-k)!)*k*(n-1) mod m
y+=(b2*c)%m; // (n-1)!*( n*(n-1)/2 + (n-1)*(n-2)/4 ) mod m
// here y should hold your answer
}
however be careful older compilers do not have full support of 64 bit integers and can produce wrong results or even does not compile. In such case use big integer lib or compute using 2*32bit variables or look for 32 bit modmul implementation.
The expression implies the use of a floating point type. Therefore, use the function fmod to get the remainder of the division.

Divide integers with floor, ceil and outwards rounding modes in C++

Recently, I saw this question which asks how you can divide integers with ceil rounding (towards positive infinity). Unfortunately the answers either don't work for signed integers or have problems with underflows and overflows.
For instance, the accepted answer has this solution:
q = 1 + ((x - 1) / y);
When x is zero, there is an underflow to ~0 and the result is incorrect.
How can you implement ceil rounding correctly for signed and unsigned integers and how do you implement other rounding modes like floor (towards negative infinity) and outwards (away from zero)?
In C++, the / division operation rounds using truncate (towards zero) by default. We can adjust the result of division towards zero to implement other rounding modes.
Note that when the division has no remainder, all rounding modes are equivalent because no rounding is necessary.
With that in mind, we can implement the different rounding modes.
But before we get started, we will need a helper template for the return types so that we don't use auto return types everywhere:
#include <type_traits>
/**
* Similar to std::common_type_t<A, B>, but if A or B are signed, the result will also be signed.
*
* This differs from the regular type promotion rules, where signed types are promoted to unsigned types.
*/
template <typename A, typename B>
using common_signed_t =
std::conditional_t<std::is_unsigned_v<A> && std::is_unsigned_v<B>,
std::common_type_t<A, B>,
std::common_type_t<std::make_signed_t<A>, std::make_signed_t<B>>>;
Ceil (towards +∞)
Ceil rounding is identical to truncate rounding for negative quotients, but for positive quotients and nonzero remainders we round away from zero. This means that we increment the quotient for nonzero remainders.
Thanks to if-constexpr, we can implement everything using only a single function:
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_ceil(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// quotient is always positive
return x / y + (x % y != 0); // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
bool quotientPositive = x >= 0;
return x / sy + (x % sy != 0 && quotientPositive); // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
bool quotientPositive = y >= 0;
return sx / y + (sx % y != 0 && quotientPositive); // uint / int
}
else {
bool quotientPositive = (y >= 0) == (x >= 0);
return x / y + (x % y != 0 && quotientPositive); // int / int
}
}
At first glance, the implementations for signed types seem expensive, because they use both an integer division and a modulo division. However, on modern architectures division typically sets a flag that indicates whether there was a remainder, so x % y != 0 is completely free in this case.
You might also be wondering why we don't compute the quotient first and then check if the quotient is positive. This wouldn't work because we already lost precision during this division, so we can't perform this test afterwards. For example:
-1 / 2 = -0.5
// C++ already rounds towards zero
-0.5 -> 0
// Now we think that the quotient is positive, even though it is negative.
// So we mistakenly round up again:
0 -> 1
Floor (towards -∞)
Floor rounding is identical to truncate for positive quotients, but for negative quotients we round away from zero. This means that we decrement the quotient for nonzero remainders.
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_floor(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// quotient is never negative
return x / y; // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
bool quotientNegative = x < 0;
return x / sy - (x % sy != 0 && quotientNegative); // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
bool quotientNegative = y < 0;
return sx / y - (sx % y != 0 && quotientNegative); // uint / int
}
else {
bool quotientNegative = (y < 0) != (x < 0);
return x / y - (x % y != 0 && quotientNegative); // int / int
}
}
The implementation is almost identical to that of div_ceil.
Away From Zero
Away from zero is the exact opposite of truncate. Basically, we need to increment or decrement depending on the sign of the quotient, but only if there is a remainder. This can be expressed as adding the sgn of the quotient onto the result:
template <typename Int>
constexpr signed char sgn(Int n)
{
return (n > Int{0}) - (n < Int{0});
};
Using this helper function, we can fully implement up rounding:
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_up(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// sgn is always 1
return x / y + (x % y != 0); // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
signed char quotientSgn = sgn(x);
return x / sy + (x % sy != 0) * quotientSgn; // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
signed char quotientSgn = sgn(y);
return sx / y + (sx % y != 0) * quotientSgn; // uint / int
}
else {
signed char quotientSgn = sgn(x) * sgn(y);
return x / y + (x % y != 0) * quotientSgn; // int / int
}
}
Unresolved Problems
Unfortunately these functions won't work for all possible inputs, which is a problem that we can not solve.
For example, dividing uint32_t{3 billion} / int32_t{1} results in int32_t(3 billion) which isn't representable using a 32-bit signed integer.
We get an underflow in this case.
Using larger return types would be an option for everything but 64-bit integers, where there isn't a larger alternative available.
Hence, it is the responsibility of the user to ensure that when they pass an unsigned number into this function, it is equivalent to its signed representation.
I would simplify and use homogeneous argument type and let the users to make explicit type casts for heterogeneous inputs, if necessary. This way possible under- and overflows are moved outside these functions. Of course normal UB cases apply, eg. divide by zero and std::numeric_limits<T>::min() divided by -1 for signed T.
#include <type_traits>
//Division round up, aka take the ceiling, aka round toward positive infinity, eg. -1.5 -> -1, 1.5 -> 2
template<typename T>
requires std::is_integral_v<T>
constexpr T divRndUp(T a, T b) noexcept
{
if constexpr (std::is_unsigned_v<T>)
return a / b + (a % b != 0);
else
return a / b + (a % b != 0 && ((a < 0) == (b < 0)));
}
//Division round down, aka take the floor, aka round toward negative infinity, eg. -1.5 -> -2, 1.5 -> 1
template<typename T>
requires std::is_integral_v<T>
constexpr T divRndDwn(T a, T b) noexcept
{
if constexpr (std::is_unsigned_v<T>)
return a / b;
else
return a / b - (a % b != 0 && ((a < 0) != (b < 0)));
}
//Division round out, aka round out away from zero, aka round toward infinity, eg. -1.5 -> -2, 1.5 -> 2
template<typename T>
requires std::is_integral_v<T>
constexpr T divRndOut(T a, T b) noexcept
{
if constexpr (std::is_unsigned_v<T>)
return a / b + (a % b != 0);
else
return a / b + (a % b != 0 && ((a < 0) == (b < 0))) - (a % b != 0 && ((a < 0) != (b < 0)));
}
//Division round in, aka truncate, aka round in toward zero, aka round away from infinity, eg. -1.5 -> -1, 1.5 -> 1
template<typename T>
requires std::is_integral_v<T>
constexpr T divRndIn(T a, T b) noexcept
{
return a / b;
}

How can I calculate (A*B)%C for A,B,C <= 10^18, in C++?

For example, A=10^17, B=10^17, C=10^18.
The product A*B exceeds the limit of long long int.
Also, writing ((A%C)*(B%C))%C doesn't help.
Assuming you want to stay within 64-bit integer operations, you can use binary long division, which boils down to a bunch of adds and multiply by two operations. This means you also need overflow-proof versions of those operators, but those are relatively simple.
Here is some Java code that assumes A and B are already positive and less than M. If not, it's easy to make them so beforehand.
// assumes a and b are already less than m
public static long addMod(long a, long b, long m) {
if (a + b < 0)
return (a - m) + b; // avoid overflow
else if (a + b >= m)
return a + b - m;
else
return a + b;
}
// assumes a and b are already less than m
public static long multiplyMod(long a, long b, long m) {
if (b == 0 || a <= Long.MAX_VALUE / b)
return a * b % m; // a*b > c if and only if a > c/b
// a * b would overflow; binary long division:
long result = 0;
if (a > b) {
long c = b;
b = a;
a = c;
}
while (a > 0) {
if ((a & 1) != 0) {
result = addMod(result, b, m);
}
a >>= 1;
// compute b << 1 % m without overflow
b -= m - b; // equivalent to b = 2 * b - m
if (b < 0)
b += m;
}
return result;
}
You can use
The GNU Multiple Precision Arithmetic Library
https://gmplib.org/
or
C++ Big Integer Library
https://mattmccutchen.net/bigint/
If you work only with power of 10 numbers, you could create a simple class with 2 members: a base and the power of 10, so A=10^17 would be {1, 17}. Implementing adding, subtracting, multiply and division is very easy and so is the print.

Neatest / Fastest Algorithm for Smallest Positive Number

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.