- 原文链接:Sum of Square Numbers (Easy)
- 题目描述:判断一个数是否为两个数的平方和。
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
/**
* 2. 两数平方和
* Input: 5
* Output: True
* Explanation: 1 * 1 + 2 * 2 = 5
* 判断一个数是否为两个数的平方和
* @author 林博弈
*
*/
public class Two_两数平方和 {
public static void main(String[] args) {
//测试用例:正常值16(true),15(false)
//边界值
//特殊值:大数、负数、null
int input = 16;
System.out.println(squareSum(input));
}
public static boolean squareSum(int n){
int start = 0;
int end = (int)Math.sqrt(n);
int sum = 0;
while(end>=start&&sum!=n){
sum = start*start+end*end;
if(sum>n)end--;
else if(sum<n)start++;
}
if(sum==n){
System.out.println(start+"*"+start+"+"+end+"*"+end+"="+sum);
return true;
}
else return false;
}
}