Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Divide and Conquer
  • MCQs on Divide and Conquer
  • Tutorial on Divide & Conquer
  • Binary Search
  • Merge Sort
  • Quick Sort
  • Calculate Power
  • Strassen's Matrix Multiplication
  • Karatsuba Algorithm
  • Divide and Conquer Optimization
  • Closest Pair of Points
Open In App
Next Article:
Largest number that is not a perfect square
Next article icon

Largest perfect square number in an Array

Last Updated : 17 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of n integers. The task is to find the largest number which is a perfect square. Print -1 if there is no number that is perfect square.
Examples: 
 

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


A Simple Solution is to sort the elements and sort the n numbers and start checking from back for a perfect square number using sqrt() function. The first number from the end which is a perfect square number is our answer. The complexity of sorting is O(n log n) and of sqrt() function is log n, so at the worst case the complexity is O(n log n).
An Efficient Solution is to iterate for all the elements in O(n) and compare every time with the maximum element, and store the maximum of all perfect squares. 
Below is the implementation of the above approach:
 

C++
// CPP program to find the largest perfect  // square number among n numbers   #include<iostream> #include<math.h> using namespace std;   // Function to check if a number  // is perfect square number or not  bool checkPerfectSquare(double n)  {      // takes the sqrt of the number      double d = sqrt(n);       // checks if it is a perfect      // square number      if (d * d == n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  int largestPerfectSquareNumber(int a[], double n)  {      // stores the maximum of all      // perfect square numbers      int maxi = -1;       // Traverse all elements in the array      for (int i = 0; i < n; i++) {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare(a[i]))              maxi = max(a[i], maxi);      }       return maxi;  }   // Driver Code  int main()  {      int a[] = { 16, 20, 25, 2, 3, 10 };       double n = sizeof(a) / sizeof(a[0]);       cout << largestPerfectSquareNumber(a, n);       return 0;  }  
C
// C program to find the largest perfect  // square number among n numbers  #include <stdio.h> #include <stdbool.h> #include <math.h>  int max(int a,int b) {   int max = a;   if(max < b)     max = b;   return max; }  // Function to check if a number  // is perfect square number or not  bool checkPerfectSquare(double n)  {      // takes the sqrt of the number      double d = sqrt(n);       // checks if it is a perfect      // square number      if (d * d == n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  int largestPerfectSquareNumber(int a[], double n)  {      // stores the maximum of all      // perfect square numbers      int maxi = -1;       // Traverse all elements in the array      for (int i = 0; i < n; i++) {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare(a[i]))              maxi = max(a[i], maxi);      }       return maxi;  }   // Driver Code  int main()  {      int a[] = { 16, 20, 25, 2, 3, 10 };       double n = sizeof(a) / sizeof(a[0]);           printf("%d",largestPerfectSquareNumber(a, n));      return 0;  }   // This code is contributed by kothavvsaakash. 
Java
// Java program to find the largest perfect  // square number among n numbers  import java.lang.Math;  import java.io.*;   class GFG {    // Function to check if a number  // is perfect square number or not  static boolean checkPerfectSquare(double n)  {      // takes the sqrt of the number      double d = Math.sqrt(n);       // checks if it is a perfect      // square number      if (d * d == n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  static int largestPerfectSquareNumber(int a[], double n)  {      // stores the maximum of all      // perfect square numbers      int maxi = -1;       // Traverse all elements in the array      for (int i = 0; i < n; i++) {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare(a[i]))              maxi = Math.max(a[i], maxi);      }       return maxi;  }   // Driver Code        public static void main (String[] args) {              int []a = { 16, 20, 25, 2, 3, 10 };       double n = a.length;       System.out.println( largestPerfectSquareNumber(a, n));       }  }  // This code is contributed  // by inder_verma..  
Python3
# Python3 program to find the largest perfect  # square number among n numbers  # from math lib import sqrt() from math import sqrt  # Function to check if a number   # is perfect square number or not def checkPerfectSquare(n) :          # takes the sqrt of the number     d = sqrt(n)          # checks if it is a perfect       # square number       if d * d == n :         return True          return False   # Function to find the largest perfect   # square number in the array   def largestPerfectSquareNumber(a, n) :          # stores the maximum of all       # perfect square numbers      maxi = -1          # Traverse all elements in the array     for i in range(n) :                  # store the maximum if current           # element is a perfect square           if(checkPerfectSquare(a[i])) :             maxi = max(a[i], maxi)          return maxi               # Driver code if __name__ == "__main__" :          a = [16, 20, 25, 2, 3, 10 ]     n = len(a)          print(largestPerfectSquareNumber(a, n))      # This code is contributed by Ryuga 
C#
// C# program to find the largest perfect  // square number among n numbers  using System; class GFG {    // Function to check if a number  // is perfect square number or not  static bool checkPerfectSquare(double n)  {      // takes the sqrt of the number      double d = Math.Sqrt(n);       // checks if it is a perfect      // square number      if (d * d == n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  static int largestPerfectSquareNumber(int []a, double n)  {      // stores the maximum of all      // perfect square numbers      int maxi = -1;       // Traverse all elements in the array      for (int i = 0; i < n; i++) {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare(a[i]))              maxi = Math.Max(a[i], maxi);      }       return maxi;  }   // Driver Code        public static void Main () {              int []a = { 16, 20, 25, 2, 3, 10 };       double n = a.Length;       Console.WriteLine( largestPerfectSquareNumber(a, n));       }  }  // This code is contributed  // by inder_verma..  
PHP
<?php // PHP program to find the largest perfect  // square number among n numbers   // Function to check if a number  // is perfect square number or not  function checkPerfectSquare($n)  {      // takes the sqrt of the number      $d = sqrt($n);       // checks if it is a perfect      // square number      if ($d * $d == $n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  function largestPerfectSquareNumber($a, $n)  {      // stores the maximum of all      // perfect square numbers      $maxi = -1;       // Traverse all elements in the array      for ($i = 0; $i <$n; $i++)     {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare($a[$i]))              $maxi = max($a[$i], $maxi);      }       return $maxi;  }   // Driver Code  $a = array( 16, 20, 25, 2, 3, 10 );   $n = count($a);  echo largestPerfectSquareNumber($a, $n);   // This code is contributed  // by inder_verma. ?> 
JavaScript
<script>  // Javascript program to find the largest perfect  // square number among n numbers  // Function to check if a number  // is perfect square number or not  function checkPerfectSquare(n)  {      // takes the sqrt of the number      let d = Math.sqrt(n);       // checks if it is a perfect      // square number      if (d * d == n)          return true;       return false;  }   // Function to find the largest perfect  // square number in the array  function largestPerfectSquareNumber(a, n)  {      // stores the maximum of all      // perfect square numbers      let maxi = -1;       // Traverse all elements in the array      for (let i = 0; i < n; i++)     {           // store the maximum if current          // element is a perfect square          if (checkPerfectSquare(a[i]))              maxi = Math.max(a[i], maxi);      }       return maxi;  }   // Driver Code  let a = [ 16, 20, 25, 2, 3, 10 ];  let n = a.length;  document.write(largestPerfectSquareNumber(a, n));   // This code is contributed by souravmahato348. </script> 

Output: 
25

 

Time Complexity : O(N * \sqrt{A_i}  )
Auxiliary Space: O(1) 


Next Article
Largest number that is not a perfect square

V

VishalBachchas
Improve
Article Tags :
  • Algorithms
  • Analysis of Algorithms
  • Divide and Conquer
  • Technical Scripter
  • DSA
  • Technical Scripter 2018
  • maths-perfect-square
Practice Tags :
  • Algorithms
  • Divide and Conquer

Similar Reads

  • Largest perfect cube number in an Array
    Given an array of N integers. The task is to find the largest number which is a perfect cube. Print -1 if there is no number that is perfect cube. Examples: Input : arr[] = {16, 8, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect cube. Input : arr[] = {36, 64, 10, 16
    7 min read
  • 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 :
    15+ min read
  • Largest number in an array that is not a perfect cube
    Given an array of n integers. The task is to find the largest number which is not a perfect cube. Print -1 if there is no number that is a perfect cube. Examples: Input: arr[] = {16, 8, 25, 2, 3, 10} Output: 25 25 is the largest number that is not a perfect cube. Input: arr[] = {36, 64, 10, 16, 29,
    8 min read
  • Largest palindromic number in an array
    Given an array of non-negative integers arr[]. The task is to find the largest number in the array which is palindrome. If no such number exits then print -1. Examples: Input: arr[] = {1, 232, 54545, 999991}; Output: 54545 Input: arr[] = {1, 2, 3, 4, 5, 50}; Output: 5 Recommended: Please try your ap
    15+ min read
  • Largest factor of a given number which is a perfect square
    Given a number [Tex]N [/Tex]. The task is to find the largest factor of that number which is a perfect square.Examples: Input : N = 420Output : 4Input : N = 100Output : 100A Simple Solution is to traverse all of the numbers in decreasing order from the given number down till 1 and if any of these nu
    10 min read
  • Largest N digit Octal number which is a Perfect square
    Given a natural number N, the task is to find the largest N digit Octal number which is a perfect square.Examples: Input: N = 1 Output: 4 Explanation: 4 is the largest 1 digit Octal number which is also perfect squareInput: N = 2 Output: 61 Explanation: 49 is the largest number which is a 2-Digit Oc
    10 min read
  • Find the Largest N digit perfect square number in Base B
    Given two integers N and B, the task is to find the largest N digit numbers of Base B which is a perfect square.Examples: Input: N = 2, B = 10 Output: 81 Explanation: 81 is the largest 2-digit perfect square in base 10.Input: N = 1, B = 8 Output: 4 Explanation: 4 is the largest 1 digit Octal number
    9 min read
  • Largest pair sum in an array
    Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
    10 min read
  • Largest Divisor of a Number not divisible by a perfect square
    Given a positive integer, N. Find the largest divisor of the given number that is not divisible by a perfect square greater than 1. Examples: Input : 12 Output : 6 Explanation : Divisors of 12 are 1, 2, 3, 4, 6 and 12. Since 12 is divisible by 4 (a perfect square), it can't be required divisor. 6 is
    12 min read
  • Smallest and Largest N-digit perfect squares
    Given an integer N, the task is to find the smallest and the largest N digit numbers which are also perfect squares.Examples: Input: N = 2 Output: 16 81 16 and 18 are the smallest and the largest 2-digit perfect squares.Input: N = 3 Output: 100 961 Approach: For increasing values of N starting from
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences