跳到正文

个人记录

连续自然数的和

gg167868约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年6月12日
收录
2026年1月10日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

不说楼上公式的方法了,直接暴力

因为本题说的是求一段 连续 的自然数的和,可以当成一个子段问题来求解。

需要解决以下几个问题: Q1 怎样得到头和尾? Q2 头和尾枚举到哪里 Q3 如果TLE,怎样优化?

按照Q1,可以直接暴力枚举头和尾,丑陋TLE代码:

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 2000010 ;
int sum[N] , n ;

int main()
{


    cin >> n ;
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            int s = (i + j) * (j - i + 1) / 2  ;
            if (s == n)
            {
                cout << i << ' ' << j << endl ;
            }
        }
    }


    return 0;
}

70分,已经是一个很不错的成绩了

考虑Q2,我们想想明白:i , j只需要枚举到n / 2 + 1(考虑到奇数的情况+1)。 同样,丑陋的TLE代码:

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 2000010 ;
int sum[N] , n ;

int main()
{


    cin >> n ;
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n / 2 + 1; j++)
        {
            int s = (i + j) * (j - i + 1) / 2 ;
            if (s == n)
            {
                cout << i << ' ' << j << endl ;
            }
        }
    }


    return 0;
}

但成绩还是定格在70。。。。。

考虑Q3,其实铺张浪费的我们其实浪费了很多时间,因为一发打中直接==n的几率很小,所以如果s已经比n大了,为什么我们还要继续增加呢? 所以只要s > n直接break,不干了 AC CODE:

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 2000010 ;
int sum[N] , n ;

int main()
{


    cin >> n ;
    for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + i ;
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n / 2 + 1; j++)
        {
            int s =(i + j) * (j - i + 1) / 2 ;
            if (s == n)
            {
                cout << i << ' ' << j << endl ;
            }
            if (s > n) break ;
        }
    }


    return 0;
}
原文