Arithmetic Progression some problems

Back to Problem Solutions forum

OrkhanAZ     2017-03-25 14:55:38

I do not understand why when using the formula in some cases, it finds it wrong and gives erroneous data. The problem itself was solved by a blunt search because for some reason the formula was not working.

int main()
{
    int str;
    int start, step, count;
    cin >> str;
    for (int i = 0; i < str; i++)
    {
        cin >> start >> step >> count;

        int sum = (((start + start) + step*(count - 1))/2)*count;// формула для вычисления суммы прогресии

        cout << sum << " ";
    }
    return 0;
}
Quandray     2017-03-25 15:26:55
User avatar

Hi,

The formula you are using does not work. If you take the case of

4 7 4

the series is 4, 11, 18, 25 with a sum of 58, but your formula gives 56.

tonychamberlain     2017-04-03 20:25:18

The series will always be this:

start, start+increment, start+2 x increment, start+3 xincrement, .. start+(count-1) x increment.

If you factor this you get

(start x count) + (1+2+3+..count-1) x increment

The formula for 1+2+..n = n(n+1)/2

so you sum should be:

int sum = start*count + (count*count-1)/2 * increment

Given Quandray's example of 4 7 4 we get:

4*4 + (4*3)/2 * 7 = 58
Please login and solve 5 problems to be able to post at forum