[POJ]1844 Sum

本文详细解析了POJ 1844 Sum问题的数学原理,通过高斯求和公式,探讨如何在指定范围内分配正负号以获得目标和。同时,提供了C++代码实现,演示了解题过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[POJ]1844 Sum

问题

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(i)=i(i+1)2

sum(i)i 所能确定的最大的数。题目肯定需要先满足:sum(i)>S,不然必然无解。
因此情况就分为:
1. sum(i)=S,此情况即为解
2. sum(i)>S,只需找到满足sum(i)S)i 值,即可。其实情况1为情况2的特殊情况。对于一个确定的 i 值,所能确定的所有和的差值必然为2的倍数 sum(i)2x)

因此,对于输入的S,可以先确定使得 sum(i)S 成立的最小 i。若 sum(i)S)i 为解。否则,若 i 为奇数,则为了保证奇偶性,需要 i+2

sum(i)S=i(i+1)2S

(i+2(i+3)2S=i(i+1)2S+2i+3

i 为偶数,则为了保证奇偶性,需要 i+1
sum(i)S=i(i+1)2S

(i+1(i+2)2S=i(i+1)2S+i+1

源代码

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int S, i;
    while (cin >> S) {
        i = (int)sqrt(2.0 * S);
        if (i * (i + 1) < 2 * S)
            ++i;
        if ((i * (i + 1) / 2 - S) % 2 == 0)
            cout << i << endl;
        else {
            if (i % 2 == 1)
                cout << i + 2 << endl;
            else
                cout << i + 1 << endl;
        }
    }
    return 0;
}

程序结果

ResultMemoryTimeLanguageCode Length
Accepted256K0MSC++333B
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值