Search code examples
javaperfect-square

How do I find perfect square from a set of numbers in Java?


So I'm trying to find out the perfect squares within a set of numbers. I declared the necessary variables, added a for loop, added a sqroot = Math.sqrt(num) and a print method to list the numbers. What I can't figure out is how can I make the program pick out the perfect squares within the range of numbers, and find the average of them?

This is for an assignment I'm working on for a class and I've been stuck on this for a while now. I'm also rather new to Java so sorry if this is a stupid question. The code is below:


public class Test {

    public static void main(String[] args) {
        int num;
        double sqroot = 0;
        int sumPsq = 0; //sum variable
        int psq = 0; //counter for perfect squares
        double avg = 0;

        for(num = 101; num <= 149; num += 2){
           sqroot = Math.sqrt(num);

            if(sqroot*sqroot == num){ //Condition to find perfect squares
                psq += 1; //counting perfect squares
                sumPsq = sumPsq + num; //Find the sum of all the perfect squares

                System.out.println(num); //Print out the perfect squares
            }
        }
        avg = 1.0 * sumPsq/psq;
        System.out.println(avg);
    }

}

This is just a piece of the code from the entire assignment, so if you need more of it then I'm more than willing to provide it. Thanks!


Solution

  • A perfect square is a number that can be expressed as the product of two equal integers so it must be an int after the sqrt. If you do a sqroot*sqroot == num you are just checking that sqrt is working correctly. Some number won't pass the check because of this but usually, you will get way more numbers than you want.

    So what you need to do is just checking that after the sqrt the result is an int:

    if (sqrootd % 1 == 0) { ... }
    

    An optimization you can do is to check the number is an integer before sqrt.   Other than that, your code looks fine to me