java - Method to calculate sum of product of two consecutive numbers -
write java method calculate following summation: 2×3+3×4+4×5+...+97×98+98×99
or more generaly, sum = 2 98 of i*(i+1).
can done recursion or for/while loop?
well have 1 product starting each number (from 2 98) rather straight forward. need loop on numbers 2 98 (with loop) , in loop add product of counter variable , counter variable + 1 sum variable initialized 0 before loop.
int sum = 0; (int = 2; < 98; i++) { sum += * (i + 1) }
whenever have repeating pattern, have use loop.
there approach this: sum i * (i + 1)
same summing i ^ 2 + i
, there formulas sum of first n numbers , first n square numbers (more on in this question). when add formulas, 1/3 * n ^ 3 + n ^ 2 + 2/3 * n
, give sum of first n squares , first n natural numbers added together. can set n 98 (as in question) , subtract 2 because don't start 1 2.
Comments
Post a Comment