四平和定理解决一个数的完全平方数组成个数
Posted 秦枫-_-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了四平和定理解决一个数的完全平方数组成个数相关的知识,希望对你有一定的参考价值。
example:求组成一个数的完全平方数的最小个数
class Solution {
public int numSquares(int n) {
if (isPerfectSquare(n)) {
return 1;
}
if (checkAnswer4(n)) {
return 4;
}
for (int i = 1; i * i <= n; i++) {
int j = n - i * i;
if (isPerfectSquare(j)) {
return 2;
}
}
return 3;
}
// 判断是否为完全平方数
public boolean isPerfectSquare(int x) {
int y = (int) Math.sqrt(x);
return y * y == x;
}
// 判断是否能表示为 4^k*(8m+7)
public boolean checkAnswer4(int x) {
while (x % 4 == 0) {
x /= 4;
}
return x % 8 == 7;
}
}
以上是关于四平和定理解决一个数的完全平方数组成个数的主要内容,如果未能解决你的问题,请参考以下文章