Sum
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 9543 | Accepted: 6248 |
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.
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
Hint
The sum 12 can be obtained from at least 7 terms in the following way: 12 = -1+2+3+4+5+6-7.
Source
Romania OI 2002
解题思路:简单数学,对于任意输入的数,先找到大于等于它的1+2+3+...+n的和的最接近值是第几个数,比如11大于等于它的是1+2+3+4+5,第五个数。接着考虑到数列中一个数i由正号变负号相当于减去2i, 分奇偶两种情况讨论,若输入的数是奇数,则应令大于等于它的数是奇数,因为只有奇数减偶数才是奇数,不是就继续加直至变成奇数,若输入的是偶数,同理应令大于等于它的数是偶数,操作同上。最后找出满足条件的是第几个数就是答案了。
解题思路:简单数学,对于任意输入的数,先找到大于等于它的1+2+3+...+n的和的最接近值是第几个数,比如11大于等于它的是1+2+3+4+5,第五个数。接着考虑到数列中一个数i由正号变负号相当于减去2i, 分奇偶两种情况讨论,若输入的数是奇数,则应令大于等于它的数是奇数,因为只有奇数减偶数才是奇数,不是就继续加直至变成奇数,若输入的是偶数,同理应令大于等于它的数是偶数,操作同上。最后找出满足条件的是第几个数就是答案了。
#include<iostream>
using namespace std;
int main()
{
long i,s,sum,ans;
while(cin>>s)
{
i=1;
sum=0;
if(s%2)
{
while(sum<s)
{
sum+=i;
i++;
}
while(sum%2==0)
{
sum+=i;
i++;
}
}
else
{
while(sum<s)
{
sum+=i;
i++;
}
while(sum%2)
{
sum+=i;
i++;
}
}
ans=i-1;
cout<<ans<<endl;
}
return 0;
}