Time Limit: 1 secs, Memory Limit: 256 MB
Description
Some numbers such as 40 can be written as the sum of consecutive integers. For example,
40 = 6 + 7 + 8 + 9 + 10.
Shiflett and Shultz defined odd-summing natural numbers as “natural numbers that are the sum of two or more consecutive [positive] odd numbers.” Perfect squares (larger than one) are always odd-summable, while primes will not be. If a number is odd-summable, there may be more than one way to express it in that manner. For example,
40 = 19 + 21 = 7 + 9 + 11 + 13
For any odd summable number n, you are to enumerate all the sets of consecutive odd positive integers that sum to the given number n.
Input
The first line of input will be the number of test cases. The remaining lines will contain one number n, 1 ≤ n ≤ 109 per line.
Output
For each problem, output one line for each solution for a number in the input set. On the line, first have the original number, followed by a colon and a space. Then have the set of consecutive odd integers whose sum is n. Output the endpoints of each set as shown in the sample output.
When multiple solutions exist, output them sorted by the first term. If no solution exists for a given n, output a single line with “impossible” instead of the set.
Sample Input
3
7
35
400
Sample Output
7: impossible
35: [3, 11]
400: [1, 39]
400: [31, 49]
400: [43, 57]
400: [97, 103]
400: [199, 201]
Problem Source
2014年每周一赛第十五场暨“指点传媒杯”第六届中山大学ICPC新手赛模拟赛
^_^ A problem about arithmetic sequence, just do it!
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
// 等差数列的基本公式
// Sn = n * a1 + n * (n - 1) * d / 2;
// an = a1 + (n - 1) * d;
int N;
bool sky = false;
cin >> N;
// begin + (begin+1)+..+ end = N => begin * i + i * (i - 1) = N => (begin + i - 1) * i = N
// i表示序列个数
// begin = N / i - i + 1
// end = begin + (i - 1) * 2
for (int i = sqrt(N); i > 1; i--)
// begin必须是大于0的整数、end必须是小于等于N的整数
// 判断begin为整数需满足 (begin + i - 1)是整数
// 此外还需注意的一点是输出序列必须为奇数序列
if (N % i == 0 && N / i - i + 1 >= 1 && N / i - i + 1 + (i - 1) * 2 <= N && (N / i - i + 1) % 2 == 1){
cout << N << ": [" << N / i - i + 1 << ", " << N / i - i + 1 + (i - 1) * 2 << "]" << endl;
sky = true;
}
// 如果未找到匹配项输出 impossible
if (!sky)
cout << N << ": impossible" << endl;
}
return 0;
}