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

1

9

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!

Unreasonable answered 3/12, 2015 at 2:5 Comment(0)
W
33

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
Walther answered 3/12, 2015 at 2:6 Comment(5)
Would the "int" before x and the "int" in the parentheses be my integer as well?Unreasonable
no. Just replace yourIntHere.Walther
Also, is there a way to negate that? As in saying if "int is not a perfect square."Unreasonable
just add else block after if and add your code in that else block.Walther
Awesome! Thank you so much you've been a big help!! :DUnreasonable

© 2022 - 2024 — McMap. All rights reserved.