(UVA) The ? 1 ? 2 ? ... ? n = k problem

 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

Alex Gevak
September 15, 2000 (Revised 4-10-00, Antonio Sanchez)


题意:通过在1到x之间添加+或者-运算,使得最后的结果等于n,输出最小的x的

值。最初想着使用BFS,提交时TLE,因为n的值太大,看到别人用到的一种数学做

法,很简单。

思路:通过1到i相加得到的和sum大于等于n,自i开始求(sum-n)%2 == 0 ,等式

不成立时sum = sum + i (i++),等式成立时输出i的值,这是的i就是要求的值。

因为sum存的是1到i的和,如果在i的时候出现“-”号 就相当于在n的基础上加了2个

i,所以差值被2整除的值所对应的就是要求的值。


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    int T;
    scanf("%d",&T);
    long long int n;
    while(T--)
    {
        long long int sum = 0;
        scanf("%lld",&n);
        if(n<0)
        {
            n = -n;
        }
        int ii  = 0;
        for(int i=1;;i++)
        {
            sum += i;
            if(sum >= n)
            {
                ii = i;
                break;
            }
        }
        if((sum - n)%2 == 0)
        {
            if(T>0)
            {
                printf("%d\n\n",ii);
            }
            else
            {
                printf("%d\n",ii);
            }
            continue;
        }
        for(int j=ii+1;;j++)
        {
            sum += j;
            if((sum-n)%2 == 0)
            {
                if(T>0)
                {
                    printf("%d\n\n",j);
                }
                else
                {
                    printf("%d\n",j);
                }
                break;
            }
        }
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶孤心丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值