题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1080
1080 两个数的平方和
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 收藏 关注给出一个整数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
思路:x*x+y*y=n => 判断 [sqrt(n-x*x)]的平方与x的平方的和是否和n相等(注:[ ] 即不超过该数的最大整数,[3.5]=3,[3]=3)
剩下的就是判重了,,,我是做一个数组,进行储存,然后遍历。。。后来看了其他人的代码发现好蛋疼——完全可以直接用x<y作
为防重条件。。。看来要走的路还很长。。。
下面贴了我自己的代码:
代码
#include <iostream>
#include <cmath>
using namespace std;
int a[100001];
int test(int x,int l)
{ int flag=0;
for(int i=0;i<l;i++)
{
if(x==a[i]) {flag=1;
break;}
}
return flag;
}
int main()
{ int n,m,x,y,flag,c,l;
while(cin>>n)
{ m=(int)sqrt((double)n);
flag=0;l=0;
for(int i=0;i<=m;i++)
{
x=i;
y=(int)sqrt((double)(n-i*i));
if(x*x+y*y==n)
{ a[l]=y;
c=test(x,l);
l++;
if(c==0)
{cout<<x<<" "<<y<<endl;
flag=1;
}
else break;
}
}
if(flag==0) cout<<"No Solution"<<endl;
}
return 0;
}