# Largest number that is not a perfect square

Given n integers, find the largest number is not a perfect square. Print -1 if there is no number that is perfect square.

Examples:

Input : arr[] = {16, 20, 25, 2, 3, 10|
Output : 20
Explanation: 20 is the largest number
that is not a perfect square
Input : arr[] = {36, 64, 10, 16, 29, 25|
Output : 29

A normal solution is to sort the elements and sort the n numbers and start checking from the back for a non-perfect square number using sqrt() function. The first number from the end which is not a perfect square number is our answer. The complexity of sorting is O(n log n) and of sqrt() function is log n, so in the worst case the complexity is O(n log n log n).

The efficient solution is to iterate for all the elements using traversal in O(n) and compare every time with the maximum element and store the maximum of all non-perfect squares. The number stored in maximum will be our answer.

Below is the illustration of the above approach:

## CPP

 // CPP program to find the largest non perfect // square number among n numbers#include using namespace std;bool check(int n){    // takes the sqrt of the number    int d = sqrt(n);     // checks if it is a perfect square number    if (d * d == n)        return true;     return false;} // function to find the largest non perfect square numberint largestNonPerfectSquareNumber(int a[], int n){    // stores the maximum of all non perfect square numbers    int maxi = -1;     // traverse for all elements in the array    for (int i = 0; i < n; i++) {         // store the maximum if not a perfect square        if (!check(a[i]))            maxi = max(a[i], maxi);    }    return maxi;} // driver code to check the above functionsint main(){    int a[] = { 16, 20, 25, 2, 3, 10 };     int n = sizeof(a) / sizeof(a[0]);    // function call    cout << largestNonPerfectSquareNumber(a, n);    return 0;}

## Java

 // Java program to find the// largest non perfect // square number among n numbers import java.io.*;  class GfG{      static Boolean check(int n){    // takes the sqrt of the number    int d = (int)Math.sqrt(n);      // checks if it is a perfect square number    if (d * d == n)        return true;      return false;}  // function to find the largest// non perfect square numberstatic int largestNonPerfectSquareNumber(int a[], int n){    // stores the maximum of all    // non perfect square numbers    int maxi = -1;      // traverse for all elements in the array    for (int i = 0; i < n; i++) {          // store the maximum if        // not a perfect square        if (!check(a[i]))            maxi = Math.max(a[i], maxi);    }    return maxi;}     public static void main (String[] args) {         int a[] = { 16, 20, 25, 2, 3, 10 };        int n = a.length;         // function call        System.out.println(largestNonPerfectSquareNumber(a, n));    }} // This code is contributed by Gitanjali.

## Python3

 # python program to find# the largest non perfect # square number among n numbers import mathdef check( n):     # takes the sqrt of the number    d = int(math.sqrt(n))      # checks if it is a    # perfect square number    if (d * d == n):        return True      return False   # function to find the largest# non perfect square numberdef largestNonPerfectSquareNumber(a, n):     # stores the maximum of all    # non perfect square numbers    maxi = -1      # traverse for all elements    # in the array    for i in range(0,n):          # store the maximum if        # not a perfect square        if (check(a[i])==False):            maxi = max(a[i], maxi)         return maxi # driver codea = [ 16, 20, 25, 2, 3, 10 ]n= len(a) # function callprint (largestNonPerfectSquareNumber(a, n)) # This code is contributed by Gitanjali.

## C#

 // C# program to find the largest non perfect // square number among n numbersusing System; class GfG {         static bool check(int n)    {                 // takes the sqrt of the number        int d = (int)Math.Sqrt(n);             // checks if it is a perfect         // square number        if (d * d == n)            return true;             return false;    }         // function to find the largest    // non perfect square number    static int largestNonPerfectSquareNumber(                               int []a, int n)    {                 // stores the maximum of all        // non perfect square numbers        int maxi = -1;             // traverse for all elements in         // the array        for (int i = 0; i < n; i++) {                 // store the maximum if            // not a perfect square            if (!check(a[i]))                maxi = Math.Max(a[i], maxi);        }                 return maxi;    }     // driver code to check the above functions    public static void Main ()    {         int []a = { 16, 20, 25, 2, 3, 10 };        int n = a.Length;         // function call        Console.WriteLine(           largestNonPerfectSquareNumber(a, n));    }} // This code is contributed by vt_m.

## Javascript



## PHP



Output
20

Time complexity can be considered as O(n) as sqrt() function can be implemented in O(1) time for fixed size (32 bit or 64 bit) integers

#### Approach#2: Using set()

This approach involves two iterations through the input array “arr”. In the first iteration, we determine all the perfect squares in the array and store them in a set. In the second iteration, we find the maximum number in the array that is not a perfect square. We accomplish this by checking each number in the array and updating the maximum number if the number is not a perfect square and is greater than the current maximum number.

#### Algorithm

1. Define a function named “is_perfect_square” that takes an integer “n” as input and returns True if “n” is a perfect square, otherwise returns False. Also define a function named “largest_non_perfect_square” that takes a list of integers “arr” as input and returns the largest number in “arr” that is not a perfect square.
2. Initialize an empty set called “perfect_squares”.
3. Iterate through “arr” and for each number:
• Check if it is a perfect square using the “is_perfect_square” function.
• If it is a perfect square, add it to the “perfect_squares” set.
4. Initialize a variable called “max_num” to -1.
5. terate through “arr” again and for each number:
1. Check if it is greater than “max_num” and not in the “perfect_squares” set.
2. If it is, update “max_num” to be the current number.
6. Return “max_num”.

## C++

 #include using namespace std; // Function to check if a number is a perfect squarebool is_perfect_square(int n) {    int root = sqrt(n);    return root * root == n;} // Function to find the largest non-perfect square in the arrayint largest_non_perfect_square(const vector& arr) {    unordered_set perfect_squares;    // Find all perfect squares in the array and store them in a set for efficient lookup    for (int num : arr) {        if (is_perfect_square(num)) {            perfect_squares.insert(num);        }    }     int max_num = -1;    // Iterate through the array to find the largest number that is not a perfect square    for (int num : arr) {        if (num > max_num && perfect_squares.find(num) == perfect_squares.end()) {            max_num = num;        }    }    return max_num;} int main() {    vector arr = {16, 20, 25, 2, 3, 10};    // Find the largest non-perfect square in the array and output the result    cout <

## Java

 import java.util.HashSet; public class Main {     // Function to check if a number is a perfect square    static boolean isPerfectSquare(int n) {        int root = (int) Math.sqrt(n);        return root * root == n;    }     // Function to find the largest non-perfect square in the array    static int largestNonPerfectSquare(int[] arr) {        HashSet perfectSquares = new HashSet<>();        // Find all perfect squares in the array and store them in a set for efficient lookup        for (int num : arr) {            if (isPerfectSquare(num)) {                perfectSquares.add(num);            }        }         int maxNum = -1;        // Iterate through the array to find the largest number that is not a perfect square        for (int num : arr) {            if (num > maxNum && !perfectSquares.contains(num)) {                maxNum = num;            }        }        return maxNum;    }     public static void main(String[] args) {        int[] arr = {16, 20, 25, 2, 3, 10};        // Find the largest non-perfect square in the array and output the result        System.out.println(largestNonPerfectSquare(arr));    }}

## Python3

 import math  def is_perfect_square(n):    return math.sqrt(n)**2 == n  def largest_non_perfect_square(arr):    perfect_squares = set()    for num in arr:        if is_perfect_square(num):            perfect_squares.add(num)    max_num = -1    for num in arr:        if num > max_num and num not in perfect_squares:            max_num = num    return max_num  arr = [16, 20, 25, 2, 3, 10]print(largest_non_perfect_square(arr))

## C#

 using System;using System.Collections.Generic; class Program{    static bool IsPerfectSquare(int n)    {        return Math.Pow(Math.Sqrt(n), 2) == n;    }     static int LargestNonPerfectSquare(int[] arr)    {        var perfectSquares = new HashSet();        foreach (var num in arr)        {            if (IsPerfectSquare(num))            {                perfectSquares.Add(num);            }        }         int maxNum = -1;        foreach (var num in arr)        {            if (num > maxNum && !perfectSquares.Contains(num))            {                maxNum = num;            }        }         return maxNum;    }     static void Main()    {        int[] arr = { 16, 20, 25, 2, 3, 10 };        Console.WriteLine(LargestNonPerfectSquare(arr));    }}

## Javascript

 function is_perfect_square(n) {    // Check if the square root of n squared is equal to n    return Math.sqrt(n) ** 2 == n;} function largest_non_perfect_square(arr) {    // Create a set to store perfect squares    let perfect_squares = new Set();    for (let num of arr) {        if (is_perfect_square(num)) {            perfect_squares.add(num);        }    }     // Find the largest non-perfect square in the array    let max_num = -1;    for (let num of arr) {        if (num > max_num && !perfect_squares.has(num)) {            max_num = num;        }    }    return max_num;} let arr = [16, 20, 25, 2, 3, 10];console.log(largest_non_perfect_square(arr));

Output
20

Time complexity: The time complexity of this approach is O(n), where “n” is the length of the input array “arr”. This is because we iterate through the array twice, once to find the perfect squares and once to find the largest non-perfect square.

Auxiliary Space: The space complexity of this approach is O(sqrt(max(arr))), where “max(arr)” is the maximum value in the input array “arr”. This is because we create a set to store the perfect squares, and the maximum number of perfect squares in the range 0 to “max(arr)” is sqrt(max(arr)).

METHOD 3:Using sqrt function

The given problem is to find the largest number that is not a perfect square in the given list of integers. We iterate through the list and check whether the square root of each number is a whole number or not. If it is not, we compare the current number with the current largest non-perfect square number found so far and update the largest accordingly.

Algorithm:

1. Initialize a variable named largest with -1.
2. Iterate through the given list of integers arr.
3. For each number, check whether its square root is a whole number or not using the modulus operator %. If the square root is not a whole number, i.e., the number is not a perfect square, and the number is greater than the current largest non-perfect square number found so far, update the largest variable with the current number.
4. Return the largest variable.

## C++

 #include #include #include  using namespace std;  int largestNonPerfectSquare(const vector& arr) {    int largest = -1;    for (int num : arr) {        if (fmod(sqrt(num), 1.0) != 0 && num > largest) {            largest = num;        }    }    return largest;} int main() {    // Example usage    vector arr = {16, 20, 25, 2, 3, 10};    cout << largestNonPerfectSquare(arr) << endl;  // Output: 20     return 0;}  // This code is contributed by shivamgupta0987654321

## Java

 import java.util.ArrayList;import java.util.List; public class LargestNonPerfectSquare {     // Function to find the largest non-perfect square number in a list    static int largestNonPerfectSquare(List arr) {        int largest = -1; // Initialize the variable to store the largest non-perfect square        for (int num : arr) { // Iterate through each number in the list            double squareRoot = Math.sqrt(num); // Calculate the square root of the number            // Check if the square root is not an integer (indicating it's not a perfect square)            // and if the current number is larger than the previously found largest non-perfect square            if (squareRoot % 1 != 0 && num > largest) {                largest = num; // Update the largest non-perfect square            }        }        return largest; // Return the largest non-perfect square found    }     public static void main(String[] args) {        // Example usage        List arr = new ArrayList<>();        arr.add(16);        arr.add(20);        arr.add(25);        arr.add(2);        arr.add(3);        arr.add(10);                 // Find and print the largest non-perfect square in the list        System.out.println(largestNonPerfectSquare(arr));     }}

## Python3

 from math import sqrt  def largest_non_perfect_square(arr):    largest = -1    for num in arr:        if sqrt(num) % 1 != 0 and num > largest:            largest = num    return largest  # Example usage:arr = [16, 20, 25, 2, 3, 10]print(largest_non_perfect_square(arr))  # Output: 20

## C#

 using System; class MainClass{    // Function to find the largest non-perfect square in an array    static int LargestNonPerfectSquare(int[] arr)    {        // Initialize the variable to store the largest non-perfect square        int largest = -1;         // Iterate through each number in the array        foreach (int num in arr)        {            // Check if the square root is not an integer (i.e., not a perfect square)            // and if the current number is greater than the current largest non-perfect square            if (Math.Sqrt(num) % 1 != 0 && num > largest)            {                // Update the largest non-perfect square                largest = num;            }        }         // Return the largest non-perfect square        return largest;    }     public static void Main(string[] args)    {        // Example usage:        int[] arr = { 16, 20, 25, 2, 3, 10 };        Console.WriteLine(LargestNonPerfectSquare(arr)); // Output: 20    }}

## Javascript

 // Importing sqrt function from the Math libraryconst sqrt = Math.sqrt; // Function to find the largest non-perfect square in an arrayfunction largest_non_perfect_square(arr) {    // Initialize the variable to store the largest non-perfect square    let largest = -1;     // Iterate through each number in the array    for (let num of arr) {        // Check if the square root is not an integer (i.e., not a perfect square)        // and if the current number is greater than the current largest non-perfect square        if (sqrt(num) % 1 !== 0 && num > largest) {            // Update the largest non-perfect square            largest = num;        }    }     // Return the largest non-perfect square    return largest;} // Example usage:let arr = [16, 20, 25, 2, 3, 10];console.log(largest_non_perfect_square(arr)); // Output: 20

Output
20

Time Complexity: The algorithm iterates through the entire list once. The square root calculation of each number takes constant time. Therefore, the time complexity of the algorithm is O(n).

Space Complexity: The algorithm uses only a constant amount of extra space to store the largest variable. Therefore, the space complexity of the algorithm is O(1).

METHOD 4:Using re

The given problem is to find the largest number in a given array that is not a perfect square.

Algorithm:

1. Define a regular expression pattern to find perfect squares.
2. Use the re module to find all perfect squares in the given array using the defined pattern.
3. Sort the list of perfect squares in descending order.
4. Iterate through the given array and return the first element that is not a perfect square.

## C++

 #include #include #include #include #include  int main() {    // Array of integers    int arr[] = {16, 20, 25, 2, 3, 10};    int n = sizeof(arr) / sizeof(arr[0]);     // Regular expression pattern to find perfect squares    std::string pattern = "\\b[1-9][0-9]*\\b";     // Find all perfect squares in the array    std::vector perfectSquares;    std::regex reg(pattern);    std::smatch match;    std::string arrString = "";    for (int i = 0; i < n; ++i) {        arrString += std::to_string(arr[i]) + " ";    }         while (std::regex_search(arrString, match, reg)) {        int num = std::stoi(match.str());        if (std::sqrt(num) - std::floor(std::sqrt(num)) == 0) {            perfectSquares.push_back(num);        }        arrString = match.suffix();    }     // Sort the array in descending order    std::sort(perfectSquares.begin(), perfectSquares.end(), std::greater());     // Find the largest number that is not a perfect square    int largestNotSquare = 0;    for (int i = 0; i < n; ++i) {        if (std::find(perfectSquares.begin(), perfectSquares.end(), arr[i]) == perfectSquares.end()) {            largestNotSquare = arr[i];            break;        }    }     // Output the result    std::cout << largestNotSquare << std::endl;     return 0;}  // This code is contributed by shivamgupta310570

## Java

 import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Main {    public static void main(String[] args) {        Integer[] arr = {16, 20, 25, 2, 3, 10};         // Regular expression pattern to find perfect squares        String pattern = "\\b[1-9][0-9]*\\b";         // Find all perfect squares in the array        List perfectSquares = new ArrayList<>();        Matcher matcher = Pattern.compile(pattern).matcher(String.join(" ", Arrays.toString(arr)));        while (matcher.find()) {            int num = Integer.parseInt(matcher.group());            if (Math.sqrt(num) % 1 == 0) {                perfectSquares.add(num);            }        }         // Sort the array in descending order        perfectSquares.sort((a, b) -> b - a);         // Find the largest number that is not a perfect square        int largestNotSquare = 0;        for (int num : arr) {            if (!perfectSquares.contains(num)) {                largestNotSquare = num;                break;            }        }         System.out.println(largestNotSquare);    }}

## Python3

 import re arr = [16, 20, 25, 2, 3, 10] # regular expression pattern to find perfect squarespattern = r'\b[1-9][0-9]*\b' # find all perfect squares in the arrayperfect_squares = [int(num) for num in re.findall(    pattern, ' '.join(map(str, arr))) if int(num)**0.5 % 1 == 0] # sort the array in descending orderperfect_squares.sort(reverse=True) # find the largest number that is not a perfect squarefor num in arr:    if num not in perfect_squares:        largest_not_square = num        break print(largest_not_square)

## C#

 using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions; class Program{    static void Main()    {        // Array of integers        int[] arr = { 16, 20, 25, 2, 3, 10 };        int n = arr.Length;         // Regular expression pattern to find perfect squares        string pattern = @"\b[1-9][0-9]*\b";         // Find all perfect squares in the array        List perfectSquares = new List();        Regex reg = new Regex(pattern);        string arrString = string.Join(" ", arr);        MatchCollection matches = reg.Matches(arrString);        foreach (Match match in matches)        {            int num = int.Parse(match.Value);            if (Math.Sqrt(num) - Math.Floor(Math.Sqrt(num)) == 0)            {                perfectSquares.Add(num);            }        }         // Sort the array in descending order        perfectSquares.Sort((a, b) => b.CompareTo(a));         // Find the largest number that is not a perfect square        int largestNotSquare = 0;        foreach (int num in arr)        {            if (!perfectSquares.Contains(num))            {                largestNotSquare = num;                break;            }        }         // Output the result        Console.WriteLine(largestNotSquare);    }}

Output
20

Time Complexity: O(nlogn)
Auxiliary Space: O(n) because we are storing the perfect squares in a list.

Previous
Next