[POJ]1844 Sum
问题
Description
Consider the natural numbers from 1 to N. By associating to each number a sign (+ or -) and calculating the value of this expression we obtain a sum S. The problem is to determine for a given sum S the minimum number N for which we can obtain S by associating signs for all numbers between 1 to N.
For a given S, find out the minimum value N in order to obtain S according to the conditions of the problem.Input
The only line contains in the first line a positive integer S (0< S <= 100000) which represents the sum to be obtained.
Output
The output will contain the minimum number N for which the sum S can be obtained.
Sample Input
12
Sample Output
7
分析
纯数学推导。。。。涉及到小学时学的高斯求和问题,即
sum(i) 是 i 所能确定的最大的数。题目肯定需要先满足:
因此情况就分为:
1. sum(i)=S ,此情况即为解
2. sum(i)>S ,只需找到满足 (sum(i)−S) 的 i 值,即可。其实情况1为情况2的特殊情况。对于一个确定的
因此,对于输入的S,可以先确定使得
sum(i)≥S
成立的最小
i
。若
若 i 为偶数,则为了保证奇偶性,需要
源代码
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int S, i;
while (cin >> S) {
i = (int)sqrt(2.0 * S);
if (i * (i + 1) < 2 * S)
++i;
if ((i * (i + 1) / 2 - S) % 2 == 0)
cout << i << endl;
else {
if (i % 2 == 1)
cout << i + 2 << endl;
else
cout << i + 1 << endl;
}
}
return 0;
}
程序结果
Result | Memory | Time | Language | Code Length |
---|---|---|---|---|
Accepted | 256K | 0MS | C++ | 333B |