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
12Sample Output
7
这道题乍看一下有点摸不着头脑~
但实际就是求sum=1+2+3+4+……+n~
当sum除以input的余数为偶数时~n为所求位数~
因为若余2*k~
当k=1时~将+1改为-1就行~
当k=2时~将+2改为-2就行~以此类推~
当余数为奇数时~则只需继续循环~加上n+1~这样余数就为偶数了~
下面是代码~
#include"stdio.h"
int main()
{
int s;
int n;
int sum;
while(scanf("%d",&s)!=EOF)
{
sum=1;
n=1;
while((sum-s)%2==1||sum<s)
{
n++;
sum+=n;
}
printf("%d\n",n);
}
return 0;
}
本文探讨了一道数学问题:通过给定的整数S,找到最小的自然数N,使得从1到N的所有整数之和能够通过调整每个数的正负号达到S。文章提供了一种有效的算法实现,并附带源代码。
270

被折叠的 条评论
为什么被折叠?



