SP31290 MATHLOVE - Math is Love 题解

· · 题解

这里提供一种解方程的做法。

首先推式子:

\because\sum\limits_{i=1}^ki=n, \therefore\frac{k(k+1)}{2}=n, \therefore k^2+k=2n,

根据一元二次方程求根公式,有

注意,因为这里 $k$ 是整数,所以 $\sqrt{1+8n}$ 是整数是有答案的必要条件,即 $1+8n$ 必须是完全平方数。 所以代码就很好写了。放代码: ```cpp #include<bits/stdc++.h> #define int long long // 记得开 long long using namespace std; main(){ ios::sync_with_stdio(false); int t; cin>>t; while(t--){ int x; cin>>x; int a=sqrt(x*8+1); if(a*a==x*8+1)cout<<(a-1>>1)<<endl; // 如果有解那么答案就是 (a-1)/2 else cout<<"NAI\n"; // 无解情况 } return 0; } ```