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:
- Calculate the value of
n. - Use the formula
n*(n+1)/2to calculate the sum of natural numbers from 1 ton.
Time complexity: O(1) Space complexity: O(1)
Optimized Solutions
Java
public class SumOfNaturalNumbers {
public static int calculateSum(int n) {
return n * (n + 1) / 2;
}
}