POJ 2853 Sequence Sum Possibilities

Sequence Sum Possibilities
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5537   Accepted: 3641

Descriptionios

Most positive integers may be written as a sum of a sequence of at least two consecutive positive integers. For instance,less

6 = 1 + 2 + 3
9 = 5 + 4 = 2 + 3 + 4
but  8 cannot be so written.

Write a program which will compute how many different ways an input number may be written as a sum of a sequence of at least two consecutive positive integers.spa

Inputcode

The first line of input will contain the number of problem instances N on a line by itself, (1 ≤ N ≤ 1000) . This will be followed by N lines, one for each problem instance. Each problem line will have the problem number, a single space and the number to be written as a sequence of consecutive positive integers. The second number will be less than 231 (so will fit in a 32-bit integer).blog

Outputip

The output for each problem instance will be a single line containing the problem number, a single space and the number of ways the input number can be written as a sequence of consecutive positive integers.input

Sample Inputstring

7
1 6
2 9
3 8
4 1800
5 987654321
6 987654323
7 987654325

Sample Outputit

1 1
2 2
3 0
4 8
5 17
6 1
7 23
題目大意:輸入一個整數n,問總共有多少個連續序列之和爲這個數。
解題方法:若是直接從0開始遍歷依次確定超時,在這裏這個序列確定爲一個公差爲1的等差數列,假設首項爲a1,長度爲i,若是知足條件,則n = a1 * i + i * (i - 1) / 2;
n -i * (i - 1) / 2 = a1 * i;也就是說n的值爲長度爲i,首項爲a1的等差數列之和,因此只要判斷(n -i * (i - 1) / 2) % i是否爲0便可,固然長度i有一個範圍,假設a1爲最小值1,那麼長度i確定爲最大值,n = i + i * (i - 1) / 2,即n = i * (i + 1) / 2,因此i的最值不會超過sqrt(n * 2.0)。
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;

int main()
{
    int nCase, index, n;
    scanf("%d", &nCase);
    while (nCase--)
    {
        int ans = 0;
        scanf("%d%d", &index, &n);
        for (int i = 2; i <= sqrt((double)n * 2.0); i++)
        {
            if ((n - i * (i - 1) / 2) % i == 0)
            {
                ans++;
            }
        }
        printf("%d %d\n", index, ans);
    }
    return 0;
}
相關文章
相關標籤/搜索