BASH - algorithm to ensure any division is even
I need a division to always return an even number
I've tried (dividend+divisor-1)/divisor and 1+(dividend-1)/divisor with no luck Code:
onk@XEON4 ~/LK/PROCESS $ dividend=1400 |
$[ ] is deprecated in bash. Instead you can try $(( arithmetic expression )). See man bash about it.
try: Code:
v=$(( dividend/2/divisor )) |
Have you tried modulus?
Code:
r=3; |
Quote:
Code:
onk@XEON4 ~/LK/PROCESS $ r=1400 |
Quote:
Code:
onk@XEON4 ~/LK/PROCESS $ echo $dividend $divisor echo $(( dividend/2/divisor*2 )) $(( dividend/divisor )) |
Quote:
"when the quotient is an integer, it will be even if and only if the dividend has more factors of two than the divisor." https://en.wikipedia.org/wiki/Parity_(mathematics) |
Maybe this (with integer aritmethic): (p+q)/(2q)*2
|
modulus would go like this:
Code:
dividend=1400; |
Quote:
$r is the result $(( dividend/divisor )) and you can use $(( r-r%2 )) to make it even. This 2 is 2 in any case, not related to divisor or anything else. |
Quote:
Code:
Evaluation is done in fixed-width integers with no check for overflow, though So in bash $(( 1400 / 3 )) will return 466 without any fractional part. I tested it to be sure and indeed, 466 was the answer. |
Quote:
Code:
onk@XEON4 ~/LK/PROCESS $ echo $dividend $divisor $((dividend/divisor - dividend/divisor%2)) |
Thanks to the others as well, modulus is good but I'm going with divide by 2 then multiply by 2 - the most obvious and good enough for my usage.
Happy New year everyone |
Quote:
Code:
onk@XEON4 ~/LK/PROCESS $ echo $dividend $divisor $((dividend/divisor)) |
Obviously you got what you were searching for because your thread is marked as [SOLVED] now but:
Out of curiosity, could you share how all of this could be useful to you? :) |
Quote:
The result of above division will be 466, with remainder 2 (which both happen to be even). |
All times are GMT -5. The time now is 09:30 AM. |