给出一个整数N,将N表示为2个整数i j的平方和(i <= j),如果有多种表示,按照i的递增序输出。
例如:N = 130,130 = 3^2 + 11^2 = 7^2 + 9^2 (注:3 11同11 3算1种)
Input
一个数N(1 <= N <= 10^9)
Output
共K行:每行2个数,i j,表示N = i^2 + j^2(0 <= i <= j)。 如果无法分解为2个数的平方和,则输出No Solution
Input示例
130
Output示例
3 11 7 9
题解:
我们先预处理出所有的平方和,一个数所含的平方和个数等于sqrt(n),如100含10个平方数,16含4个平方数,之后暴力枚举所有的平方数,计算出与之对应的平方数,需要注意的是3 11 和11 3是同一组数据,不能重复输出,在这里我们把预处理的平方和设为0即可。注意1 输出 0 1 4输出0 2
代码:
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
const int maxn=100000;
long long a[maxn];
int main()
{
for(int i=0;i<maxn;i++)
{
a[i]=i*i;
}
long long n;
cin>>n;int flag=0;
long long len=(long long)sqrt(n);
for(int i=0;i<len;i++)
{
long long num=n-a[i];
long long ans=(long long)(sqrt(num));
if(sqrt(num)==ans){
cout<<i<<" "<<ans<<endl;
a[ans]=0;flag=1;
}
}
if(!flag) cout<<"No Solution"<<endl;
return 0;
}