
Problem
Solution
Submissions
Sum of the First 'n' Natural Numbers
Certification: Basic Level
Accuracy: 66.67%
Submissions: 3
Points: 5
Write a C++ program that calculates the sum of the first 'n' natural numbers.
Example 1
- Input: n = 5
- Output: 15
- Explanation:
- Step 1: Identify the first n natural numbers: 1, 2, 3, 4, 5.
- Step 2: Calculate the sum: 1 + 2 + 3 + 4 + 5 = 15.
- Step 3: Return the sum: 15.
Example 2
- Input: n = 10
- Output: 55
- Explanation:
- Step 1: Identify the first n natural numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
- Step 2: Calculate the sum: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
- Step 3: Return the sum: 55.
Constraints
- 1 ≤ n ≤ 10^6
- Note: You can use the mathematical formula: sum of first n natural numbers = n(n+1)/2
- Time Complexity: O(1) when using the formula
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the formula: n * (n + 1) / 2
- Handle edge case where n = 1 explicitly
- Ensure calculations avoid integer overflow