virtual hust 2013.6.23 数学杂题基础题目 E - The ? 1 ? 2 ? ... ? n = k problem

题目:The ? 1 ? 2 ? ... ? n = k problem

思路:这个跟喵呜上次出的题一样,因为求的值化简一下就是sum(1...n)-2*subsum(1..n)=k,那么我们就只要保证(sum(1...n)-k)%2==0就行了,因为那个subsum是可以遍历1 to sum(1..n)的数的,同时要保证它大于0

== 我直接交上次写的代码,结果WA了,原因在于多少还是有个trick的,output里有说n是大于等于1的,那么当k=0时,我的程序跑出来答案是0,很明显这个应该特判,答案是3(1+2-3)。

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
long long sum(long long n)
{
    return n*(n+1)/2;
}
int main()
{
    long long n;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);
        if(n==0)
            printf("3\n");
        else
        {
            if(n<0)
                n*=-1;
            long long ans=0;
            for(;;ans++)
            {
                if(sum(ans)>=n&&(sum(ans)-n)%2==0)
                {
                    printf("%lld\n",ans);
                    break;
                }
            }
        }
        if(t)
            printf("\n");
    }
    return 0;
}
View Code

 

posted @ 2013-06-23 10:01  over_flow  阅读(154)  评论(0编辑  收藏  举报