-2

If I want to find the total number of odd integers between a leftrange and a rightrange, do you think this works ?

example leftrange = 3, rightrange = 8.

int FindOdd(int left, int right)
{
   bool lefteven  = (left  % 2) ? false: true;
   bool righteven = (right % 2) ? false: true;
   int length = (right-left) + 1;

   if (lefteven != righteven) //even length
   {
      return (length/2);
   }

   else //odd length
   {
      if (!lefteven)
          return ((length/2) + 1);

      else
          return (length/2);
   }
}
  • 1
    You tell us. Which values did you use to test? And what were the results of that test? – Bathsheba Feb 09 '18 at 12:42
  • 2
    `bool lefteven = (left % 2) ? false: true;` --> `bool lefteven = !(left % 2);` – Arnav Borborah Feb 09 '18 at 12:43
  • 1
    Duplicate of https://stackoverflow.com/questions/652292/what-is-unit-testing-and-how-do-you-do-it – UKMonkey Feb 09 '18 at 12:47
  • 1
    If your code does work; I would suggest posting it on https://codereview.stackexchange.com/ to get further feedback. – UKMonkey Feb 09 '18 at 12:49
  • I'd upvote an answer that uses metaprogramming: e.g. `foo<3, 8>::value`. – Bathsheba Feb 09 '18 at 12:52
  • Here is a theoretical solution on Mathematics SE: [How do I determine the number of odd integers in a range?](https://math.stackexchange.com/questions/138865/how-do-i-determine-the-number-of-odd-integers-in-a-range). Wrap it into an algorithm. – Ron Feb 09 '18 at 13:23

1 Answers1

3

It's a clumsy way to do it. A better way is to use integer division:

unsigned FindOdd(unsigned a, unsigned b)
{
    return b / 2 - a / 2;
}

This will not include the final number if b is odd. I've cheekily changed the types to unsigned for the sake of elegance.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483