https://www.luogu.org/problemnew/show/P1147
descriptive heading
for a given natural number M, to obtain a natural number of all consecutive segments, the successive natural numbers and the sum of the total number of segments M.
Example: 1998 + 1999 + 2000 + 2001 + 2002 = 10000, so a solution from a natural number 10000 1998-2002 period is M =.
Input Output Format
Input Format:
contains an integer value of M given in a single line (10≤M≤2,000,000).
Output format:
each row two natural numbers, given in a successive natural numbers satisfying the condition number of a first segment and a last number, separated by a space between the two numbers, a first output for all rows in ascending ascending order, for a given input data, to ensure that there is at least one solution.
Input Output Sample
Input Sample # 1:
10000
Output Sample # 1:
18 142
297 328
388 412
1998 2002
/ *
Way1: data not to be considered directly enumerate + half
way2: Faster certainly is mathematical derivation of
* /
Way1 (O (nlogn)):
#include <iostream>
using namespace std;
typedef long long LL;
int main()
{
LL m;
cin>>m;
for(int i = 0; i < m; i++)
{
LL s = i,e = -1;
LL low = s+1,high = m-1,mid;
while(low <= high)
{
mid = (low + high) / 2;
LL temp = (s + mid) * (mid - s + 1);//这里int不够
if(temp < 2 * m)
{
low = mid + 1;
}
else if(temp > 2 * m)
{
high = mid - 1;
}
else
{
e = mid;
break;
}
}
if(e != -1)
{
cout<<s<<" "<<e<<endl;
}
}
return 0;
}
way2 (O (n)):
mathematical derivation:
Summation The arithmetic:
sum = (s+e) * (e-s+1) / 2
(s+e) *(e-s+1) = 2 * sum
设 s + e = x1,
e-s+1 = x2;
解上述方程组:e = (x1+x2-1)/2, s = (x1-x2+1)/2;
再由第二个表达式:x1 * x2 = 2*sum
可知2*sum一定为偶数,那么x1,x2可能有两种情况:
1.两个都是偶数
2.一奇一偶
根据 e = (x1+x2-1)/2, s = (x1-x2+1)/2; 并且要是自然数解,
那么x1+x2-1与x1-x2+1必定要为偶数,
so可以排除第一种情况,所以x1,x2必定一奇一偶
根据x1,x2必定一奇一偶,
枚举其中一个,根据x1 * x2 = 2*sum得出另一个,
再根据 e = (x1+x2-1)/2, s = (x1-x2+1)/2就可以求出结果了。
比如枚举x2,根据x1 * x2 = 2*sum,确定x2的上限:
up <= sqrt(2*sum),
后续看代码~
#include <iostream>
#include <math.h>
using namespace std;
typedef long long LL;//其实int就够
int main()
{
LL m;
cin>>m;
LL s,e,x1,x2;
LL up= sqrt(2*m);
for(int i = up; i > 1; i--)//逆序枚举x2,因为影响s,e起主导作用的是x1
{
x2 = i;
x1 = 2 * m / x2;
if(((x2&1) && !(x1&1)) || (!(x2&1) && (x1&1)))
{
if(x1 * x2 == 2*m)
{
s = (x1 - x2 + 1) >> 1;
e = (x1 + x2 - 1) >> 1;
cout<<s<<" "<<e<<endl;
}
}
}
return 0;
}