poj 1844 Sum

本文探讨了一道数学问题:通过给定的整数S,找到最小的自然数N,使得从1到N的所有整数之和能够通过调整每个数的正负号达到S。文章提供了一种有效的算法实现,并附带源代码。

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

 

这道题乍看一下有点摸不着头脑~

但实际就是求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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值