Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an integer is a perfect square [duplicate]

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!

like image 600
Brooke Avatar asked Dec 03 '15 02:12

Brooke


People also ask

How do you check if an integer is a perfect square?

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.

Is there a number whose repeat is 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.

How do you know if a number is a perfect square without Squarert?

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.


1 Answers

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
like image 189
Jaskaranbir Singh Avatar answered Oct 22 '22 19:10

Jaskaranbir Singh