balazscseh
balazscseh

Reputation: 9

The sum of the first n elements of a geometric series within an arithmetic series II

Task description:

Calculate the sum of the first n elements of a series s1, s2 = s1 + d1, s3 = s2 + d2, ... where the differences d1, d2, ... between the elements form a geometric series. The function receives the first three elements of the series (first, second and third) as well as n values. The return value of the function is the sum s1 + ... + sn. The nth element of the geometric series: dn = d1 * q ^ (n-1)

The first test case:

struct {double first; double second; double third; int n; double sum;} testlist[1] = {
            {1.0, 3.0, 7.0, 5, 57.0},
            {1.0, 2.0, 2.5, 5, 11.125}

My code is: (with the help of Oli L)

double series(double first, double second, double third, int n) {

    if(n <= 0) return 0;
    double d1 = second-first;
    double d2 = third-second;
    double q = d2/d1;
    
    double s[n];
    double d[n];

    double result = q;

    s[0] = first;
    d[0] = d1;
    double sum = s[0];

    for( int i = 1 ; i < n ; i++) {
        
        d[i] = d1*result;
        result*=q;

        s[i] = s[i-1] + d[i-1];
        sum += s[i];
    }
    return sum;
}

Unfortunately, I don’t see any more test cases and I can’t extract the main function either, as I have to upload my code to a strict page that tests it after pasting it into the encrypted frame.

So far, with a little help, I've gotten as far as I can, 4 out of 5 test cases run successfully, but one (which I don't see) isn't good. I would ask for ideas on what the problem might be, what an extreme case I might not have thought, or what the code might look like then.

Upvotes: 0

Views: 482

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224082

The sequence 0, 0, 0,… is a geometric sequence (it satisfies di = d1qi−1 by using 0 for q) that is not handled by the code in the question. For this series of differences, all the si are equal. Notably, first, second, and third have the same value.

When this occurs, d1 and d2 are set to 0 by these lines:

double d1 = second-first;
double d2 = third-second;

and then double q = d2/d1; sets q to a NaN (Not a Number, a “value” used in floating-point to indicate there is no suitable real number). This NaN propagates through other calculations, causing the routine to return a NaN.

When the sequence is a sequence of identical terms with zero differences, the sum of n terms is n*first. So the code in the question can be corrected by handling this case just after the test for n <= 0:

if (first == second && second == third)
    return n*first;

Upvotes: 0

Related Questions