如何得到一个没有小数点的数字的平方根?



我的问题很直接,如果我想得到一个数字的平方根,比如343,那么数学。SQRT得到18.520....但我想要的输出是7√7。

我怎么能做到呢?

import java.lang.Math;
import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to get Simplified Square root -");
long num = sc.nextLong();
long max = (long) Math.sqrt(num);
long outsideRoot = 1L;

while (num % 4 == 0){
outsideRoot *= 2;
num /= 4;
}

for (long i = 3L; i < max; i+=2){
while (num % (i*i) == 0){
outsideRoot *= i;
num /= (i*i);
}
}

System.out.println(outsideRoot
+"root"+num); 
}
}

我目前正在使用这个代码,它似乎工作得很好,直到现在从Utkarsh Sahu的代码的一些灵感。这段代码的执行速度要快得多,而Utkarsh的代码需要4-5秒,考虑到它是一台计算机,这是一个巨大的时间。对于这段代码的想法,欢迎在评论中提出。

试试下面的代码片段。

import java.util.*;
class SquareRoot{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked");
long num = sc.nextLong();
long temp = num, a = 1;
String root = "";
for(long i = 2; i <= temp; i++){
if(temp % (i*i) == 0){
a *= i;
temp /= (i*i);
i--;
}

}
root = (temp != 1) ? a+"root"+temp : a+"";
//In place of writing root, you can use squareroot symbol too
System.out.println("Square root of "+num+" = "+root);
sc.close();
}
}

在显示(打印)部分,我的键盘上没有平方根符号,所以我不能输入它,只能输入&;root&;代替。如果你愿意,你也可以使用这个符号。

编辑:变量的数据类型已经根据您的需要从int更改为long

最新更新