在 Java 中查找小于给定数字的最大平方
Finding largest square less than a given number in Java
我想编写一个 java 程序来找到小于或等于给定数字的最大平方数。
For example when I insert 10
as the inputted number, the answer is 9
because 9
is the largest square up to 10
我理解循环,但我无法弄清楚这背后的逻辑。
像下面这样的东西如何让你继续......
double x = 20;
double root = Math.sqrt(x);
int t = (int)root;
System.out.println("Root is:" + root + " and answer is :" + t*t);
这里是如何用循环来做到这一点
int n=10; //This is your Number
int i = 0;
for(i=n;i>=1;i--)
if((int)Math.sqrt(i)*(int)Math.sqrt(i)==i)
break;
System.out.println(i);
下面是它的工作原理:-
循环从 n
(您的号码)到 1
。然后检查 i
的平方根,即 运行 到 n
到 1
,是否是 perfect square
。如果是,它 breaks
loop
,并在屏幕上打印 i
的值。
public static void main(String argv[]){
System.out.println(largestSquareLessOrEqualTo(145));
}
public static int largestSquareLessOrEqualTo(int limit){
int i = 0;
for (; i <(int)Math.sqrt(limit); i++){
}
return(i*i);
}
我想编写一个 java 程序来找到小于或等于给定数字的最大平方数。
For example when I insert
10
as the inputted number, the answer is9
because9
is the largest square up to10
我理解循环,但我无法弄清楚这背后的逻辑。
像下面这样的东西如何让你继续......
double x = 20;
double root = Math.sqrt(x);
int t = (int)root;
System.out.println("Root is:" + root + " and answer is :" + t*t);
这里是如何用循环来做到这一点
int n=10; //This is your Number
int i = 0;
for(i=n;i>=1;i--)
if((int)Math.sqrt(i)*(int)Math.sqrt(i)==i)
break;
System.out.println(i);
下面是它的工作原理:-
循环从 n
(您的号码)到 1
。然后检查 i
的平方根,即 运行 到 n
到 1
,是否是 perfect square
。如果是,它 breaks
loop
,并在屏幕上打印 i
的值。
public static void main(String argv[]){
System.out.println(largestSquareLessOrEqualTo(145));
}
public static int largestSquareLessOrEqualTo(int limit){
int i = 0;
for (; i <(int)Math.sqrt(limit); i++){
}
return(i*i);
}