Write a Java method to calculate the following summation: 2×3+3×4+4×5+...+97×98+98×99
Or more generaly, the sum from i = 2 to 98 of i*(i+1).
Can this be done with recursion or only with a for/while loop?
Write a Java method to calculate the following summation: 2×3+3×4+4×5+...+97×98+98×99
Or more generaly, the sum from i = 2 to 98 of i*(i+1).
Can this be done with recursion or only with a for/while loop?
Well as you have one product starting with each number (from 2 to 98) this is rather straight forward. All you need to do is loop over all numbers from 2 to 98 (with a for loop) and then in this loop you add the product of the counter variable and the counter variable + 1 to a sum variable which is initialized with 0 before the loop.
int sum = 0;
for (int i = 2; i < 98; i++) {
sum += i * (i + 1)
}
Whenever you have a repeating pattern, you will probably have to use a loop.
There also is another approach to this: Sum i * (i + 1)
this is the same as summing i ^ 2 + i
and there are formulas for the sum of the first n numbers and first n square numbers (More on those in this question). When you add the to formulas, you get 1/3 * n ^ 3 + n ^ 2 + 2/3 * n
, which will give you the sum of the first n squares and the first n natural numbers added together. You can then set n to 98 (as in your question) and the subtract 2 because the you don't start with 1 but with 2.