gpt4 book ai didi

java - 可以计算 2 个区间之间的数字的最大平方根次数

转载 作者:行者123 更新时间:2023-12-02 05:30:01 26 4
gpt4 key购买 nike

我写了一个简单的程序来计算一个数字可以计算平方根的最大次数,输入是从num1到num2的区间例如:如果输入是 (1,20),则答案为 2,因为 16 的平方根是 4 ,而 4 的平方根是 2 。

 int max = 0;
for (int i = num1; i <= num2; i++) {
boolean loop = true;
int count = 0;
int current = i;
if (i == 1) {
count++;
} else {
while (loop) {
double squareRoot = Math.sqrt(current);
if (isCurrentNumberPerfectSquare(squareRoot)) {
count++;
current = (int) squareRoot;
} else {
loop = false;
}
}
}

if (count > max) {
max = count;
}
}
return max;


static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - floor(number)) == 0);
}

我得到了答案,但想知道是否可以使用某种数学方法来改进?有什么建议吗?

最佳答案

为了避免更多困惑,我在此给​​出对这个主题的最终答案。前面提到的两种方法的组合。

“Parameswar”正在寻找的是由最低底形成的最大完美正方形。

Step 1 -
To get that calculate the largest possible perfect square based on your num2 value.
If it is outside your range, you have no perfect square within.

Step 2 -
If it is within your range, you have to check all perfect square formed by a lower base value with a higher number of times.

Step 3 -
If you find one that is within your range, replace your result with the new result and proceed to check lower values. (go back to Step 2)

Step 4 -
Once the value you check is <= 2 you have already found the answer.

这里有一些示例实现:

    static class Result {
int base;
int times;
}

static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - Math.floor(number)) == 0);
}

private static int perfectSquare(int base, int times) {

int value = base;
for (int i = times; i > 0; i--) {
value = (int) Math.pow(base, 2);
}
return value;
}

private static Result calculatePerfectSquare(int perfectSquare) {

Result result = new Result();
result.base = (int) Math.sqrt(perfectSquare);
result.times = 1;

while (result.base > 2 && isCurrentNumberPerfectSquare(Math.sqrt(result.base))) {
result.base = (int) Math.sqrt(result.base);
result.times += 1;
}

System.out.println(perfectSquare + " -> " + result.base + " ^ " + result.times);
return result;
}

static int maxPerfectSquares(int num1, int num2) {

int largestPerfectSqr = (int) Math.pow(Math.floor(Math.sqrt(num2)), 2);
if (largestPerfectSqr < num1) {
return 0;
}

Result result = calculatePerfectSquare(largestPerfectSqr);

int currentValue = result.base;

while (currentValue > 2) {

// check lower based values
currentValue--;

int newValue = perfectSquare(currentValue, result.times + 1);
if (newValue >= num1 && newValue < num2) {

result = calculatePerfectSquare(newValue);
currentValue = result.base;
}
}

return result.times;
}

关于java - 可以计算 2 个区间之间的数字的最大平方根次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56206877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com