4

"An array is used to store ten integer numbers. Write a Java program that determines and print the square numbers which are also odd numbers from the given array."

The problem I have is how to figure out if the number in the array is a square number. I tried this way but it's not correct!

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 output it gives me

run:
25
81
55
25
55

55 is there too that means this method I used is not successful!

laish138
  • 243
  • 1
  • 2
  • 10
  • I guess you mean the numbers must be squares of integers only since every positive number is a square of some real number. Hence you could check whether `y` is an integer (i.e. the fraction part is 0 or at least very small because of precision issues). – Thomas Apr 18 '16 at 08:20
  • Check this [link](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) – greenPadawan Apr 18 '16 at 08:23

3 Answers3

5

You could just 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);
    }
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
5

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.

If you know x is an int you shouldn't get a rounding error and you can do

int x = ...
double sqrt = Math.sqrt(x);
if ((int) sqrt == sqrt)
    // we have a square.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

hope this will be much easier,

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

In here inside if condition first I check whether number is an odd number by taking modulus division and the 2nd condition check whether number is a perfect square. First I get the square root of given number and then take the modulus division by 1 and check whether it's equal to 0. If number is a perfect square, square root of that number is an integer, when I take the modulus division of an integer answer should be equal to 0.

Isuru
  • 129
  • 7