Sum-1844

Sum
Time Limit: 1000MS
Memory Limit: 30000K
Total Submissions: 10504
Accepted: 6900

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

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

这个题就是考你的数学分析能力,把算法搞明白了,那剩下的code就很easy了。
算法分析:
假如:s = 12
sum = 1+2+3+4+5+6+7
sum -1-7之后:
2+3+4+5+6
然后再减去1和7,就是-1+2+3+4+5+6-7=12
我们把sum叫做A,把-1-7叫做X,结果s叫做B
我们发现,如果X存在,那么有这么一个关系式:
A - 2X = B
从而A - B = 2X
也就是说A - B为偶数
看看人家的分析:
1+2+3+4+5+6+7+8+9+10....因为在A中少加一数X(只能有+,-不加必减)相当于A-2X=B;
要让X存在.A-B必为偶数.只要有一数A能减去给出的数B的结果C为偶数的话就一定可了.

sum就是上面说的A,
在例子中的12,输出7。
演示如下:1+2+3+4+5这时为15比12大了但是-12为3(X不能存在)。再加6为21,-12为9(X不能存在)。再加7为28,-12为16,这说明X为8就可以了,在1+2+3+4+5+6+7中要-8就写成-1+2+3+4+5+6-7。又因为28-12=16的16是sum-n的第一个偶数。因此X=8也是第一个合符题意的数。为什么要求要sum-n的第一个偶数吗?上面说了因为在sum中少加一数X(只能有+,- 不加必减)相当于sum-2X=n;X=(sum-n)/2,X必为整数,这就要求(sum-n)能整除2.


代码实现如下:

#include 
   
   
    
    
int main(void)
{
	int i = 1;
	long s,sum = 0;
	scanf("%ld",&s);
	while((sum < s) || (sum - s) % 2 != 0)
	{
		sum += i;
		i++;
	}
	printf("%d\n",i - 1);
	return 0;
}
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值