uva10025(数学)

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=12&problem=966&mosmsg=Submission+received+with+ID+10537466

10025 - The ? 1 ? 2 ? ... ? n = k problem

Time limit: 3.000 seconds

The ? 1 ? 2 ? ... ? n = k problem

The problem

Given the following formula, one can set operators '+' or '-' instead of each '?', in order to obtain a given k
? 1 ? 2 ? ... ? n = k

For example: to obtain k = 12 , the expression to be used will be:
- 1 + 2 + 3 + 4 + 5 + 6 - 7 = 12
with n = 7

The Input

The first line is the number of test cases, followed by a blank line.

Each test case of the input contains integer k (0<=|k|<=1000000000).

Each test case will be separated by a single line.

The Output

For each test case, your program should print the minimal possible n (1<=n) to obtain k with the above formula.

Print a blank line between the outputs for two consecutive test cases.

Sample Input

2

12

-3646397

Sample Output

7
2701
题意:±1 ± 2 ± 3 ±…± n = k , 找出满足条件的最小 n 。。
这题做的时间跨越好久啊,今天看了无数的解题报告终于小懂了。(没有优化)

必然存在整数 x(1=< x <= n)满足:


当 s1 = 1+2+3+...+x+..+n >= k时,有 s2 = 1+2+3+...-x+..+n == k,即多出的x肯定在1~n之间。


s1 - s2 = s1 - k = 2x


所以,我们想求最小的n,也就是求最小的满足条件的s1,而它与k的差必为偶数,剩下的暴力找就可以了。


通过求和公式,求出前n个和比k大的n的最小值,然后判断前n个数的和与k的值的差是否为偶数,如果为偶数则表示该n为最小的所需个数,因为如果差为偶数,则只需将前n个数的几个数前的符号改为减号,就可以得到k,如果不为偶数,则n的值加一,重复以上判断。直到出现符合以上判断的n的出现,则是最小的n的值。


#include<stdio.h>
#include<math.h>
int main()
{
 int t;
 int flag=0;
 scanf("%d",&t);
 while(t--)
 {
  int k;
  scanf("%d",&k);
  if(flag>0)
   printf("\n");
  flag++;
  if(k<0)//正负的处理是一样的
   k=-k;
  int sum=0;
  for(int i=1;;i++)
  {
   sum+=i;
   if(sum>=k&&(sum-k)%2==0)
   {
    printf("%d\n",i);
    break;
   }
  }
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值