Skip to main content
3 of 6
added 1 character in body
JanB
  • 83
  • 1
  • 5

Finding all possible pairs of square numbers in an array

I am writing a program that allows me to find all possible pairs of square numbers. e.g an array of {5,25,3,25,4,2,25} will return [5,25],[5,25],[2,4],[5,25] since 25 is square of 5

currently, i am using a nested for loop to find the squares. I'm just wondering if there is a better way to do this?

import java.lang.Math.*;

public static void main(String args[])
{
    int arr[] = {25,25,3,25,4,2,5};
    String s = "";
    
    for(int i =0; i < arr.length;i++)
    {

        for(int j = 0;j < arr.length;j++)
        {
            if(Math.sqrt(arr[i]) == arr[j])
            {
                s += arr[j] + "," + arr[i] + " ";
            }
        }
        
    }
    
    System.out.println(s);

}
JanB
  • 83
  • 1
  • 5