[POJ]1844 Sum

来源:互联网 发布:海尔智能软件下载 编辑:程序博客网 时间:2024/06/05 11:56

[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(i+1)2

sum(i)i 所能确定的最大的数。题目肯定需要先满足:sum(i)>S,不然必然无解。
因此情况就分为:
1. sum(i)=S,此情况即为解
2. sum(i)>S,只需找到满足sum(i)S)i 值,即可。其实情况1为情况2的特殊情况。对于一个确定的 i 值,所能确定的所有和的差值必然为2的倍数 sum(i)2x)

因此,对于输入的S,可以先确定使得 sum(i)S 成立的最小 i。若 sum(i)S)i 为解。否则,若 i 为奇数,则为了保证奇偶性,需要 i+2

sum(i)S=i(i+1)2S

(i+2(i+3)2S=i(i+1)2S+2i+3

i 为偶数,则为了保证奇偶性,需要 i+1
sum(i)S=i(i+1)2S

(i+1(i+2)2S=i(i+1)2S+i+1

源代码

#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
0 0