4月 04, 2009

【解題】Odd Sum

@
ACM Volume CVII 10783 - Odd Sum


The Problem

Given a range [a, b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3, 9] is 3 + 5 + 7 + 9 = 24.


Input

There can be at multiple test cases. The first line of input gives you the number of test cases, T (1 ≤ T ≤ 100). Then T test cases follow. Each test case consists of 2 integers a and b (0 ≤ ab ≤ 100) in two separate lines.


Output

For each test case you are to print one line of output - the serial number of the test case followed by the summation of the odd integers in the range [a, b].


Sample Input

2
1
5
3
5


Sample Output

Case 1: 9
Case 2: 8


解題思考

  對於這一題的解,我們可以將之視為一個等差級數:首項為大於等於 a 的最小奇數 a'、末項為小於等於 b 的最大奇數 b'、項數為 (b' - a' + 2) / 2。

  根據以上,我們便可以直接利用等差級數和的公式:[(a' + b') × (b' - a' + 2) / 2] / 2 = (a' + b') × (b' - a' + 2) / 4。

  套用這個公式,答案就出來囉。


參考解答(C++)

#include <iostream>

using namespace std;

int main(void)
{
    int t;
    cin >> t;
    for (int i = 1; i <= t; i++)
    {
        int a, b;
        cin >> a >> b;

        if (a % 2 == 0) { a++; }
        if (b % 2 == 0) { b--; }

        cout << "Case " << i << ": " << ((a + b) * (b - a + 2)) / 4 << endl;
    }

#ifndef ONLINE_JUDGE
    system("pause");
#endif

    return 0;
}

0 回覆:

張貼留言