Design a class to overload a function sumSeries() as follows: (i) void sumSeries(int n, double x) - with one integer argument and one double argument, to find and display the sum of the series: x/1 + x/2 + x/3 + ... + x/n (ii) void sumSeries() - to find and display the sum of the following series: s = 1 + (1 x 2) + (1 x 2 x 3) + ... + (1 x 2 x 3 x ... x 20)
Topic: Method overloading — two series
Answer
class SumSeries { void sumSeries(int n, double x) { double s = 0.0; for(int i = 1; i <= n; i++) s = s + x / i; System.out.println("Sum = " + s); }
void sumSeries() { long s = 0L, f = 1L; for(int i = 1; i <= 20; i++) { f = f * i; s = s + f; } System.out.println("Sum = " + s); }
public static void main(String args[]) { SumSeries ob = new SumSeries(); ob.sumSeries(5, 10.0); ob.sumSeries(); } }
Two methods named sumSeries(), told apart by their parameter lists — (int, double) and none at all.
The first series divides x by each term number in turn. Because x is already a double, x / i is floating-point division and no cast is needed — but note that if both were ints, the fractions would be lost entirely.
The second series is the clever one. Each term is a factorial, and recomputing 20! from scratch every time would be wasteful. Instead keep a running factorial f: multiply it by i at each pass, and it becomes 1!, 2!, 3! ... in turn, ready to be added to the sum. One loop, no nesting.
The data type matters here: 20! is about 2.4 x 10^18, far beyond the range of int (roughly 2.1 x 10^9). Both s and f must be declared long, or the answer silently overflows into nonsense. Recognising when a value outgrows int is exactly what this question is testing.
n int - number of terms in the first series x double - the numerator of each term in the first series i int - loop variable s double / long - running total of the series f long - running factorial, giving 1!, 2!, 3! and so on ob SumSeries - object used to invoke the methods