How could I write an if-then statement that checks if an inputted integer is a perfect square or not (i.e. if I took the square root, it would be an integer as well: 4, 9, 16, 25, 36, etc.) in DrJava? Thank you!
All perfect squares end in 1, 4, 5, 6, 9 or 00 (i.e. Even number of zeros). Therefore, a number that ends in 2, 3, 7 or 8 is not a perfect square.
Hence (1011+1)⋅100⋅23⋅4093⋅8779=8264462810082644628100 is a repeated number and a perfect square! Checking this on wolfram alpha shows that this number is indeed a square.
Suppose we have a number n, we have to check whether n is a perfect square number or not. A perfect square number k can be represented as k = a * a for some integer a. We have to solve this without using built-in square root function. So, if the input is like n = 121, then the output will be True because 121 = 11*11.
I am aware that this question already has an answer.... But just in case, this also works.
int x = (int) Math.sqrt(input);
if(Math.pow(x,2) == input)
//Do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With