Write a program to find the sum of the given series 1+2+3+ . . . . . .(N terms)
Example 1:
Input:
N = 1
Output: 1
Explanation: For n = 1, sum will be 1.
Example 2:
Input:
N = 5
Output: 15
Explanation: For n = 5, sum will be 15.
1 + 2 + 3 + 4 + 5 = 15.
Ans:
class Solution {
public static long seriesSum(int n) {
// code
if(n == 1){
return 1;
}
long s = 0;
for(int i = 1; i <= n; i++){
s = s+i;
} return s;
}
}
Note: 1) time complexity will be O(N), because using 1 loop
2) we can start i from 0th index also
Using recursion:
class Solution {
public static long seriesSum(int n) {
// Base Case
if (n == 1) {
return 1;
}
// Recursive Case: Sum of series up to (n - 1) + n
return seriesSum(n - 1) + n;
}
}
Comments
Post a Comment