描述:
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.
输入:
The only line contains in the first line a positive integer S (0< S <= 100000) which represents the sum to be obtained.
输出:
The output will contain the minimum number N for which the sum S can be obtained.
输入样例:
12
0
输出样例:
7
3
解题思路:先对1~N求和,求出最大的范围,然后每当减一个数就是要减掉两倍的,就是减去偶数,所以只要Sum-sum是偶数即可。
代码如下:
- #include<iostream>
- usingnamespacestd;
- intmain()
- {
- intstate=0;
- intn;
- cin>>n;
- for(inti=1;;i++)
- {
- ints=i*(i+1)/2;
- if(s<n)
- continue;
- if((s-n)%2==0)
- {
- cout<<i<<endl;
- break;
- }
- }
- return0;
- }