1116: 我家的门牌号

1116: 我家的门牌号

题目描述
我家住在一条短胡同里,这条胡同的门牌号从1开始顺序编号。
若其余各家的门牌号之和减去我家门牌号的两倍,恰好等于n,求我家的门牌号及总共有多少家。数据保证有唯一解。
输入
一个正整数n。n<100000。
输出
一行,包含两个正整数,分别是我家的门牌号及总共有多少家,中间用单个空格隔开。

样例输入
100
样例输出
12 16

#include <iostream>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int sum = (1 + n) * n / 2;
    int x = 1;
    while (1)
    {
        int i = ((1 + x) * x / 2 - n) / 3;
        if ((1 + x) * x / 2 - 3 * i == n && i >= 1)
        {
            cout << i << " " << x;
            break;
        }
        x++;
    }
    return 0;
}

img

【以下回答由 GPT 生成】

解决方案如下:

  1. 首先,我们可以假设我家的门牌号为x,总共有多少家为total。根据题目给出的条件,求出公式:total * (total + 1) / 2 - x * 2 = n。(total * (total + 1) / 2是所有门牌号之和)

  2. 根据上面的公式,我们可以将问题转化为求解x和total。我们可以通过遍历total来求解x和total。

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int x, total;

    for (total = 1; total < n; total++) {
        x = (total * (total + 1) / 2 - n) / 2;
        if (x >= 1 && x <= total) {
            break;
        }
    }

    cout << x << " " << total << endl;
    return 0;
}

该代码的时间复杂度为O(n),其中n为给定的正整数。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^