题目
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.
A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!
Input
The first input line contains an integer n (1 ≤ n ≤ 109).
Output
Print "YES" (without the quotes), if n can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes).
Examples
Input
256
Output
YES
Input
512
Output
NO
题目大意
输入一个数n,判断这个数n能够表示成 A*(A+1)/2 + B*(B+1)/2的形式 (也就是n?=A*(A+1)/2 + B*(B+1)/2)
如果可以输出YES,否则输出NO
思路:二分
代码
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
long long n,low,high,mid;
cin>>n;
int flag=0;
for(long long i=1;i<sqrt(2*n);i++)
{
long long t=i*(i+1)/2;
low=1;high=sqrt(2*(n-t));mid=(low+high)/2;
while(low<=high)
{
if(t+mid*(mid+1)/2==n) {flag=1;break;}
else if(t+mid*(mid+1)/2>n) {high=mid-1;mid=(low+high)/2;}
else {low=mid+1;mid=(low+high)/2;}
}
if(flag==1) break;
}
if(flag==0) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
return 0;
}
A通过for循环从1开始找
然后B通过二分来找