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

📅  最后修改于: 2021-04-22 09:50:50             🧑  作者: Mango

给定范围L和R,任务是找到范围L至R的所有自然数之和。
例子

Input: L = 2, R = 5
Output: 14
2 + 3 + 4 + 5 = 14

Input: L = 10, R = 20
Output: 165

天真的方法是从L遍历到R,然后将所有元素一一相加以获得总和。
一种有效的方法是将公式用于前N个自然数的总和。包含-排除原理的思想有助于解决上述问题。找出直到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 natural numbers
int sumNatural(int n)
{
    int sum = (n * (n + 1)) / 2;
    return sum;
}
 
// Function to return the sum
// of all numbers in range L and R
int suminRange(int l, int r)
{
    return sumNatural(r) - sumNatural(l - 1);
}
 
// Driver Code
int main()
{
    int l = 2, r = 5;
    cout << "Sum of 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
 
class GFG{
// Function to return the sum of
// all natural numbers
static int sumNatural(int n)
{
    int sum = (n * (n + 1)) / 2;
    return sum;
}
 
// Function to return the sum
// of all numbers in range L and R
static int suminRange(int l, int r)
{
    return sumNatural(r) - sumNatural(l - 1);
}
 
// 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 "+suminRange(l, r));
 
}
}
// This code is contributed by mits


Python3
# Python3 program to print the sum  of
# all numbers in range L and R
 
# Function to return the sum of all natural numbers
def sumNatural(n):
 
    sum = (n*(n+1))//2
 
    return sum
 
# Function to return the sum
# of all numbers in range L and R
def suminRange(l, r):
    return sumNatural(r) - sumNatural(l-1)
 
#  Driver Code
l =2; r= 5
print("Sum of Natural numbers 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 natural numbers
static int sumNatural(int n)
{
    int sum = (n * (n + 1)) / 2;
    return sum;
}
 
// Function to return the sum
// of all numbers in range L and R
static int suminRange(int l, int r)
{
    return sumNatural(r) -
           sumNatural(l - 1);
}
 
// Driver Code
static public void Main ()
{
    int l = 2, r = 5;
    Console.WriteLine("Sum of Natural numbers " +
                              "from L to R is " +
                               suminRange(l, r));
}
}
 
// This code is contributed by akt_mit


PHP


Javascript


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