Java Square Numbers

"An array is used to store ten integers. Write a Java program that defines and prints square numbers, which are also odd numbers from this array."

The problem is how to find out if the number in the array is a square number. I tried this way, but it is not right!

import java.math.*;
public class JavaApplication43 {

    public static void main(String[] args) {

        int[] no = {22, 44, 25, 89, 81, 55, 23, 25, 55};

        for (int i = 0; i < no.length; i++) {

            int x = no[i];
            double y;
            if (x % 2 != 0) {
                y = Math.sqrt(x);
                if (x == (Math.pow(y, 2))) 
                    System.out.println(no[i]);
            }
       }
   }
}

This is the result that he gives me

run:
25
81
55
25
55

55 there is also, which means that this method that I used was unsuccessful!

+4
source share
3 answers

You can simply do:

for (int i = 0; i < no.length; i++) {
    int x = no[i];
    if (x % 2 == 0) continue;
    int y = (int) Math.sqrt(x);
    if (x == y * y) { 
        System.out.println(x);
    }
}
+5
source

You can determine if a number is a square by checking if its square root is an integer.

double sqrt = Math.sqrt(x);
long sqrt2 = Math.round(sqrt);
if (Math.abs(sqrt - sqrt2) / sqrt < 1e-15)
   // we have a square.

, x - int, ,

int x = ...
double sqrt = Math.sqrt(x);
if ((int) sqrt == sqrt)
    // we have a square.
+5

, ,

    if((arr[i]%2 != 0) & (Math.sqrt(arr[i])%1 == 0)){
        System.out.println(arr[i]);
    }

, , , , , . , 1 , 0. , , 0.

+2

All Articles