Sum Of Numbers
find the sum of the given series. if the given number is n, the sum is 1+2+3+4+5.......+n.
Example 1:
Input:
N = 10
Output: 55
Explanation: For n = 10, sum will be 10+9+8+7+6+5+4+3+2+1=55
Example 2:
Input:
N = 5
Output: 15
Explanation: For n = 5, sum will be 1
+ 2 + 3 + 4 + 5 = 15.
Method 1:
First, a variable sum is initialized to 0. Then, the function enters a loop that continues while n is greater than 0. In each iteration of the loop, the current value of n is added to the sum, and then n is decremented by 1. Once the loop completes, the final value of the sum is returned.
java implementation:
class codemummy {
long seriesSum(int n) {
long sum=0;
while(n>0){
sum=sum+n;
n--;
}
return sum;
}
}
Time Complexity: O(n)
space Complexity: O(1)
space Complexity: O(1)
c++ implementation:
long seriesSum(int n) { long sum=0; while(n>0){ sum=sum+n; n--; } return sum; }
Time Complexity: O(n)
space Complexity: O(1)
space Complexity: O(1)
python implementation:
def seriesSum(n): sum = 0 while n > 0: sum += n n -= 1 return sum
Time Complexity: O(n)
space Complexity: O(1)
space Complexity: O(1)
method 2 :
use formula:
java implementation:
class Solution {
long seriesSum(int n) {
long m=n;
return (m*(m+1))/2;
}
}
Time Complexity: O(1)
space Complexity: O(1)
space Complexity: O(1)
c++ implementation:
long seriesSum(int n) { long m = n; return (m * (m + 1)) / 2; }
Time Complexity: O(1)
space Complexity: O(1)
space Complexity: O(1)
python implementation:
def seriesSum(n): return (n * (n + 1)) // 2
Time Complexity: O(1)
space Complexity: O(1)
space Complexity: O(1)
No comments