Friday, 14 June 2024

Natural Sum in C++

Problem Description
You are given a positive integer 'N'. You have to find the sum of the first 'N' natural numbers.

Input format
First line contains an integer - N.

Output format
Print the sum of first N natural numbers.

Sample Input 1
10

Sample Output 1
55

Explanation
1+2+3+4+5+6+7+8+9+10 = 55

Constraints
1 <= N <= 10^4

Solution
To find the sum of the first \( N \) natural numbers, we can use the well-known formula for the sum of an arithmetic series. The sum of the first \( N \) natural numbers is given by:

\[ \text{Sum} = \frac{N \times (N + 1)}{2} \]

This formula allows us to compute the sum in constant time \( O(1) \), which is very efficient.

### Steps to Implement the Solution
1. Read the integer \( N \) from input.
2. Compute the sum using the formula.
3. Print the computed sum.

Here is the C++ code that implements this solution:

#include <iostream>
using namespace std;

int main() {
    int N;
    cin >> N;
    
    // Using the formula to calculate the sum of first N natural numbers
    int sum = (N * (N + 1)) / 2;
    
    // Output the sum
    cout << sum << endl;
    
    return 0;
}

### Explanation
1. **Input Handling**: The program reads an integer \( N \) from the standard input.
2. **Sum Calculation**: Using the formula \(\frac{N \times (N + 1)}{2}\), the sum of the first \( N \) natural numbers is calculated.
3. **Output**: The program prints the calculated sum.

### Sample Run

#### Sample Input 1
10

#### Sample Output 1
55

#### Explanation
The sum of the first 10 natural numbers is \( 1 + 2 + 3 + \ldots + 10 = 55 \).

This program efficiently computes the sum of the first \( N \) natural numbers even for the upper limit \( N = 10^4 \) due to the constant time complexity of the arithmetic series formula.

No comments:

Post a Comment