📜  L和R范围内的所有奇数自然数之和

📅  最后修改于: 2021-05-07 01:02:07             🧑  作者: Mango

给定两个整数L和R,任务是查找范围L和R中的所有奇数自然数之和。
例子

Input: L = 2, R = 5
Output: 8
3 + 5 = 8

Input: L = 7, R = 13
Output: 40

天真的方法是从L遍历到R并求和以求答案。
一种有效的方法是使用公式来计算直到RL-1的所有奇数自然数的和,然后减去sum(R)-sum(L-1)
下面是上述方法的实现:

C++
// C++ program to print the sum
// of all numbers in range L and R
#include 
using namespace std;
 
// Function to return the sum of
// all odd natural numbers
int sumOdd(int n)
{
    int terms = (n + 1) / 2;
    int sum = terms * terms;
    return sum;
}
 
// Function to return the sum
// of all odd numbers in range L and R
int suminRange(int l, int r)
{
    return sumOdd(r) - sumOdd(l - 1);
}
 
// Driver Code
int main()
{
    int l = 2, r = 5;
    cout << "Sum of odd natural numbers from L to R is "
         << suminRange(l, r);
 
    return 0;
}


Java
// Java program to print the sum
// of all numbers in range L and R
 
import java.io.*;
 
class GFG {
    
 
 
// Function to return the sum of
// all odd natural numbers
static int sumOdd(int n)
{
    int terms = (n + 1) / 2;
    int sum = terms * terms;
    return sum;
}
 
// Function to return the sum
// of all odd numbers in range L and R
static int suminRange(int l, int r)
{
    return sumOdd(r) - sumOdd(l - 1);
}
 
// Driver Code
public static void main (String[] args) {
            int l = 2, r = 5;
    System.out.print( "Sum of odd natural numbers from L to R is "
        + suminRange(l, r));
    }
}
// This code is contributed by shs..


Python3
# Python 3 program to print the sum
# of all numbers in range L and R
 
# Function to return the sum of
# all odd natural numbers
def sumOdd(n):
    terms = (n + 1)//2
    sum1 = terms * terms
    return sum1
 
# Function to return the sum
# of all odd numbers in range L and R
def suminRange(l, r):
    return sumOdd(r) - sumOdd(l - 1)
     
# Driver code
l = 2; r = 5
print("Sum of odd natural number",
      "from L to R is", suminRange(l, r))
 
# This code is contributed by Shrikant13


C#
// C# program to print the sum
// of all numbers in range L and R
using System;
 
class GFG
{
     
// Function to return the sum of
// all odd natural numbers
static int sumOdd(int n)
{
    int terms = (n + 1) / 2;
    int sum = terms * terms;
    return sum;
}
 
// Function to return the sum
// of all odd numbers in range L and R
static int suminRange(int l, int r)
{
    return sumOdd(r) - sumOdd(l - 1);
}
 
// Driver Code
public static void Main ()
{
    int l = 2, r = 5;
    Console.WriteLine( "Sum of odd natural numbers " +
                "from L to R is " + suminRange(l, r));
}
}
 
// This code is contributed by shs..


PHP


Javascript


输出:
Sum of odd natural numbers from L to R is 8