用一个函数实现求两数之间所有数的平方和(Java)(函数可真难,脑子不够用了)
这个问题有点含糊,假设两个数是递增的。而且是整数且结果包括x和y,那可以参考一下我的回答:
public class Test {
public static void main(String[] args) {
int x,y;
System.out.println("请输入两个数x,y");
Scanner scanner = new Scanner(System.in);
x = scanner.nextInt();
y = scanner.nextInt();
System.out.println("x到y之间的数字平方和是"+sumMulti(x,y));
}
public static int sumMulti(int x,int y){
int sum = 0;
for (int i = x; i <= y; i++) {
sum = sum + i*i;
}
return sum;
}
}
望采纳!
public boolean twoSquareSum(int target) {
if (target < 0) return false;//如果输入的整数为负数,则不存在平方和
int i = 0, j = (int) Math.sqrt(target);//分别定义了左指针和右指针
while (i <= j) {//循环条件至少要满足左指针不会移到右指针右侧
int powSum = i * i + j * j;//求平方和
if(powSum == target) {//if else判断两数平方和powSum与target是否相等
return true;
} else if (powSum > target) {
j--;
} else {
i++;
}
}
return false;
}
}