Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 10504 | Accepted: 6900 |
Description
For a given S, find out the minimum value N in order to obtain S according to the conditions of the problem.
Input
Output
Sample Input
12
Sample Output
7
Hint
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;
}