gpt4 book ai didi

java - 在进行平方之前如何计算超过 100 万所需的平方数

转载 作者:行者123 更新时间:2023-12-02 12:07:21 25 4
gpt4 key购买 nike

此代码提示用户输入一个有效的整数,并重复该整数的平方,直到超过 100 万。它也是类型安全的。有没有一种方法可以计算出在我的程序执行任何平方之前整数超过 100 万所需的平方数?

import java.util.Scanner;

public class Squaring{

public static void main (String [] args) {

Scanner scan = new Scanner(System.in);
long number;
long number2;
int count = 0;
number = getInt("Enter an integer greater than 1:",scan);

while ( number <= 1) {
scan.nextLine();
System.out.println(number +" is not greater than 1.");
number = getInt("Enter an integer greater than 1:",scan);

}
number2 = number;
while ( number < 1000000) {
number = number * number;
System.out.println(number);
count++;
}

System.out.println(number2 + " exceeded 1,000,000 after "+ count + " squarings."); }

public static int getInt(String prompt, Scanner scan) {

int input;
System.out.println( prompt );
while ( !scan.hasNextInt() ) {
String garbage = scan.nextLine();
System.out.println( garbage + " is not valid input.\n" + prompt);
}

input = scan.nextInt();

return input;
}
}

最佳答案

是的。不好意思使用更优雅的代数方法,请使用基于预先计算和向后计算的 if-check:

1e6
^ 0.5 = 1000 (1)
^ 0.5 ~= 31.6 (2)
^ 0.5 ~= 5.6 (3)
^ 0.5 ~= 2.4 (4)
^ 0.5 ~= 1.5 (5)

由于您已经指定了整数输入(并假设为正),因此您可以快速获得一些界限。超过一百万:

  • 1 或更小的值永远不会到达那里,
  • 值为 2 将需要 5 次平方运算,
  • 值 3 到 5 将需要 4 次平方运算,
  • 值 6 到 31 将进行 3 次平方运算,
  • 值 32 到 999 将进行 2 次平方运算,
  • 并且值 1000 到 999,999 只需进行 1 次平方运算。

现在您的算法已简化为简单的 if 检查。

关于java - 在进行平方之前如何计算超过 100 万所需的平方数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801764/

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