📜  L和R范围内的所有偶数之和

📅  最后修改于: 2021-04-26 10:40:28             🧑  作者: Mango

给定两个整数L和R,任务是查找范围L和R中的所有偶数之和。

例子:

Input: L = 2, R = 5 
Output: 6
2 + 4 = 6

Input: L = 3, R = 8
Output: 18

方法1:从L到R进行迭代,并将该范围内的所有偶数加起来。

方法2:找到从L到R的所有自然数之和,并从中减去L到R范围内的奇数自然数之和。

方法3:

  • 找出不超过R的所有偶数之和,即不超过R的偶数的个数将为R / 2
  • 找出不超过L-1的所有偶数之和,即不超过L-1的偶数的数目为(L-1)/ 2
  • 然后从sumuptoR减去sumUptoL。

下面是上述方法的实现:

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


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


Python3
# Python 3 program to print the sum 
# of all even numbers in range L and R 
  
# Function to return the sum  
# of all natural numbers 
def sumNatural(n):
    sum = (n * (n + 1))
    return int(sum)
  
# Function to return sum 
# of even numbers in range L and R 
def sumEven(l, r):
    return (sumNatural(int(r / 2)) - 
            sumNatural(int((l - 1) / 2)))
  
# Driver Code 
l, r = 2, 5
print("Sum of Natural numbers", 
             "from L to R is", sumEven(l, r)) 
  
# This code is contributed 
# by 29AjayKumar


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


PHP


输出:
Sum of Natural numbers from L to R is 6