在进行任何平方之前,如何计算超过100万的平方数

时间:2017-10-18 02:06:50

标签: java

此代码提示用户输入有效整数并重复平方整数,直到超过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;
} 
}

1 个答案:

答案 0 :(得分:1)

是。害羞使用更优雅的代数方法,使用基于预先计算的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-check。