-3

I am looking to identify method in Java 8 which says square root of any number is complete or not.

For ex:

Math.sqrt(25) gives 5.0
Math.sqrt(49) gives 7.0
Math.sqrt(30) gives 5.477225575051661

So when given number is complete sqrt, need to written true else false, how can we simply do this?

Jeff Cook
  • 7,956
  • 36
  • 115
  • 186
  • 5
    Can you define what you mean by "complete"? Is `Math.sqrt(1.44)` complete? – Joachim Sauer Jul 02 '21 at 12:23
  • What do you mean by "complete"? Do you mean "square root is an integer"? Note that `sqrt` is the function name, but the name to use when talking about the math is "square root". – Alan Jul 02 '21 at 12:24
  • Complete means its gives value washout decimal values. Why you're downvoting it ? I have clearly given example – Jeff Cook Jul 02 '21 at 12:25
  • 4
    *"I have clearly given example"* - but not generic enough examples. E.g. the root of 1.44 is 1.2 which may or may not be accepted by your code. – luk2302 Jul 02 '21 at 12:26
  • @JeffCook "washout"? Do you mean "without". Computing is about getting details right and clear. Sorry if English is not your first language. – Alan Jul 02 '21 at 12:27
  • 3
    @JeffCook: three example don't make a specification. If your question was totally clear, I wouldn't have posted my comment abd it wouldn't have been upvoted. – Joachim Sauer Jul 02 '21 at 12:27

4 Answers4

2

You could compare the square root to the floor of the square root and check if they're equal:

public static boolean hasCompleteSqrt(double d) {
    double sqrt = Math.sqrt(d);
    return sqrt == Math.floor(sqrt);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

if the ceil or floor is equal to the number...

x  =  Math.sqrt(25);

if (x==Math.ceil(x)||x==Math.floor(x))
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • If `x` is an integer then `Math.ceil()` is the same value as `Math.floor()`, no need to check both. Or am I missing something here? – Joachim Sauer Jul 02 '21 at 12:28
0

You can use Math.floor:

double notInteger = Math.sqrt(30);
double integer = Math.sqrt(25);

notInteger == Math.floor(notInteger); // false
integer == Math.floor(integer); // true
tomrlh
  • 1,006
  • 1
  • 18
  • 39
0

you can check if square root of number is whole number or not as below

 if((Math.sqrt(25)) % 1 == 0) {
                System.out.println("it is whole number");
            } else {
                System.out.println("it is not whole number");
            }
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24