POJ 1844 Sum

题意:给一个整数n,求当n由1到k的连续整数加或减组成时的最小的k。

 

解法:一开始觉得dp……后来觉得复杂度太大了……GG……百度了一下是个数学题orz。

如果n全部由加法组成,那么k可以组成k(k+1)/2,设减掉的部分为s,则有k(k+1)/2-2s=n,所以n和k(k+1)/2mod2同余。

 

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<iomanip>
#define LL long long
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1

using namespace std;

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i = (int)sqrt(n); ; i++)
        {
            int tmp = (i * i + i) / 2;
            if(tmp < n) continue;
            if((tmp & 1) == (n & 1))
            {
                cout << i << endl;
                break;
            }
        }
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/Apro/p/4946042.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值