📜  计算从L到R范围内的奇数和偶数

📅  最后修改于: 2021-05-04 17:59:41             🧑  作者: Mango

给定两个数字L和R,任务是计算L到R范围内的奇数个数。

例子:

方法:该范围内的总数将为(R – L +1),即N。

  1. 如果N为偶数,则奇数和偶数的计数均为N / 2
  2. 如果N是奇数
    • 如果L或R为奇数,则奇数的计数将为N / 2 +1 ,偶数= N – countofOdd
    • 否则,奇数的计数将为N / 2 ,偶数的计数将为N – countofOdd

下面是上述方法的实现:

C++
// C++ implementation of the above approach 
#include 
  
using namespace std;
  
// Return the number of odd numbers 
// in the range [L, R] 
int countOdd(int L, int R){ 
  
    int N = (R - L) / 2;
  
    // if either R or L is odd 
    if (R % 2 != 0 || L % 2 != 0) 
        N += 1;
  
    return N;
}
  
// Driver code
int main()
{ 
    int L = 3, R = 7;
    int odds = countOdd(L, R); 
    int evens = (R - L + 1) - odds; 
      
    cout << "Count of odd numbers is " << odds << endl; 
    cout << "Count of even numbers is " << evens << endl;
    return 0;
}
  
// This code is contributed by Rituraj Jain


Java
// Java implementation of the above approach
  
class GFG {
  
    // Return the number of odd numbers
    // in the range [L, R]
    static int countOdd(int L, int R)
    {
        int N = (R - L) / 2;
  
        // if either R or L is odd
        if (R % 2 != 0 || L % 2 != 0)
            N++;
  
        return N;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int L = 3, R = 7;
  
        int odds = countOdd(L, R);
        int evens = (R - L + 1) - odds;
        System.out.println("Count of odd numbers is " + odds);
        System.out.println("Count of even numbers is " + evens);
    }
}


Python 3
# Python 3 implementation of the 
# above approach
  
# Return the number of odd numbers
# in the range [L, R]
def countOdd(L, R):
  
    N = (R - L) // 2
  
    # if either R or L is odd
    if (R % 2 != 0 or L % 2 != 0):
        N += 1
  
    return N
  
# Driver code
if __name__ == "__main__":
      
    L = 3
    R = 7
  
    odds = countOdd(L, R)
    evens = (R - L + 1) - odds
    print("Count of odd numbers is", odds)
    print("Count of even numbers is", evens)
  
# This code is contributed by ita_c


C#
// C# implementation of the above approach 
using System;
  
class GFG
{ 
  
    // Return the number of odd numbers 
    // in the range [L, R] 
    static int countOdd(int L, int R) 
    { 
        int N = (R - L) / 2; 
  
        // if either R or L is odd 
        if (R % 2 != 0 || L % 2 != 0) 
            N++; 
  
        return N; 
    } 
  
    // Driver code 
    public static void Main() 
    { 
        int L = 3, R = 7; 
  
        int odds = countOdd(L, R); 
        int evens = (R - L + 1) - odds; 
        Console.WriteLine("Count of odd numbers is " + odds); 
        Console.WriteLine("Count of even numbers is " + evens); 
    } 
} 
  
// This code is contributed by Ryuga


PHP


输出:
Count of odd numbers is 3
Count of even numbers is 2