702732. Sum of Natural Numbers

Basic

Sum of Natural Numbers

Summary

This problem involves calculating the sum of natural numbers from 1 to n. The key concept involved is the mathematical series, and the goal is to develop an efficient algorithm to compute the sum.

Detailed Explanation

The sum of natural numbers from 1 to n can be calculated using a simple formula: n*(n+1)/2. This formula is based on the mathematical property that the sum of the first n natural numbers is equal to the average of the first and last terms multiplied by the number of terms.

Here's a step-by-step breakdown of the solution:

  1. Calculate the value of n.
  2. Use the formula n*(n+1)/2 to calculate the sum of natural numbers from 1 to n.

Time complexity: O(1) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class SumOfNaturalNumbers {
    public static int calculateSum(int n) {
        return n * (n + 1) / 2;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.