simplest one line code to calculate the amount of even integers in a range {n1,n2} (n1,n2 included )

37 Views Asked by At

I have experimented a bit but havent found something that works for all four cases . the cases are :

Odd-Odd

**Odd-even

Even-Odd**

Even-Even

the highlited cases work the same because the amount of even integers in a range {2n+1,2m} is the same as in the range {2n,2m+1} ex.

R1={2,5} amount of evens : 2 namely 2,4

R2={3,6} amount of evens : 2 namely 4,6

Id be really happy if any of you can help me :)

1

There are 1 best solutions below

4
Dave On

Here's a simple one-liner: n2/2 - (n1-1)/2

Here's Ruby code that implements this. The / is integer division.

def f(small, big)
  return big/2 - (small-1)/2
end

> f(4,8)
=> 3
> f(4,9)
=> 3
> f(5,8)
=> 2
> f(5,9)
=> 2

Negative examples

> f(-9, -5)
=> 2
> f(-9, -4)
=> 3
> f(-8, -5)
=> 2
> f(-8, -4)
=> 3