Print all perfect squares from the given range - GeeksforGeeks

08 Apr, 2021
Given a range [L, R], the task is to print all the perfect squares from the given range.Examples:  
Input: L = 2, R = 24 Output: 4 9 16Input: L = 1, R = 100 Output: 1 4 9 16 25 36 49 64 81 100  
 
Naive approach: Starting from L to R check whether the current element is a perfect square or not. If yes then print it.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){     // For every element from the range    for (int i = l; i <= r; i++) {         // If current element is        // a perfect square        if (sqrt(i) == (int)sqrt(i))            cout << i << " ";    }} // Driver codeint main(){    int l = 2, r = 24;     perfectSquares(l, r);     return 0;}
//Java implementation of the approachimport java.io.*; class GFG{     // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){     // For every element from the range    for (int i = l; i <= r; i++)    {         // If current element is        // a perfect square        if (Math.sqrt(i) == (int)Math.sqrt(i))            System.out.print(i + " ");    }} // Driver codepublic static void main (String[] args){    int l = 2, r = 24;    perfectSquares(l, r);}} // This code is contributed by jit_t
# Python3 implementation of the approach # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r):     # For every element from the range    for i in range(l, r + 1):         # If current element is        # a perfect square        if (i**(.5) == int(i**(.5))):            print(i, end=" ") # Driver codel = 2r = 24 perfectSquares(l, r) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{     // Function to print all the perfect// squares from the given rangestatic void perfectSquares(int l, int r){     // For every element from the range    for (int i = l; i <= r; i++)    {         // If current element is        // a perfect square        if (Math.Sqrt(i) == (int)Math.Sqrt(i))            Console.Write(i + " ");    }} // Driver codepublic static void Main(String[] args){    int l = 2, r = 24;    perfectSquares(l, r);}} // This code is contributed by 29AjayKumar
<script>// js implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){     //For every element from the range    for (let i = l; i <= r; i++)    {           // If current element is        // a perfect square        if (Math.sqrt(i) == parseInt(Math.sqrt(i)))            document.write(i + " ");    }} // Driver codelet l = 2;let r = 24;perfectSquares(l, r) // This code is contributed by sravan.</script>
4 9 16
 
It is solution with O(n). moreover the use of number of square roots leads to computational expense.Efficient approach: This method is based on the fact that the very first perfect square after number L will definitely be the square of ⌈sqrt(L)⌉. In very simple terms, the square root of L will be very close to the number whose square root we are trying to find. Therefore, the number will be pow(ceil(sqrt(L)), 2). The very first perfect square is important for this method. Now the original answer is hidden over this pattern i.e. 0 1 4 9 16 25 the difference between 0 and 1 is 1 the difference between 1 and 4 is 3 the difference between 4 and 9 is 5 and so on... which means that the difference between two perfect squares is always an odd number.Now, the question arises what must be added to get the next number and the answer is (sqrt(X) * 2) + 1 where X is the already known perfect square.Let the current perfect square be 4 then the next perfect square will definitely be 4 + (sqrt(4) * 2 + 1) = 9. Here, number 5 is added and the next number to be added will be 7 then 9 and so on... which makes a series of odd numbers.Addition is computationally less expensive than performing multiplication or finding square roots of every number.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the perfect// squares from the given rangevoid perfectSquares(float l, float r){     // Getting the very first number    int number = ceil(sqrt(l));     // First number's square    int n2 = number * number;     // Next number is at the difference of    number = (number * 2) + 1;     // While the perfect squares    // are from the range    while ((n2 >= l && n2 <= r)) {         // Print the perfect square        cout << n2 << " ";         // Get the next perfect square        n2 = n2 + number;         // Next odd number to be added        number += 2;    }} // Driver codeint main(){    int l = 2, r = 24;     perfectSquares(l, r);     return 0;}
// Java implementation of the approachclass GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){     // Getting the very first number    int number = (int) Math.ceil(Math.sqrt(l));     // First number's square    int n2 = number * number;     // Next number is at the difference of    number = (number * 2) + 1;     // While the perfect squares    // are from the range    while ((n2 >= l && n2 <= r))    {         // Print the perfect square        System.out.print(n2 + " ");         // Get the next perfect square        n2 = n2 + number;         // Next odd number to be added        number += 2;    }} // Driver codepublic static void main(String[] args){    int l = 2, r = 24;     perfectSquares(l, r); }} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach from math import ceil, sqrt # Function to print all the perfect# squares from the given rangedef perfectSquares(l, r) :      # Getting the very first number    number = ceil(sqrt(l));     # First number's square    n2 = number * number;     # Next number is at the difference of    number = (number * 2) + 1;     # While the perfect squares    # are from the range    while ((n2 >= l and n2 <= r)) :         # Print the perfect square        print(n2, end= " ");         # Get the next perfect square        n2 = n2 + number;         # Next odd number to be added        number += 2; # Driver codeif __name__ == "__main__" :     l = 2; r = 24;     perfectSquares(l, r); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to print all the perfect// squares from the given rangestatic void perfectSquares(float l, float r){     // Getting the very first number    int number = (int) Math.Ceiling(Math.Sqrt(l));     // First number's square    int n2 = number * number;     // Next number is at the difference of    number = (number * 2) + 1;     // While the perfect squares    // are from the range    while ((n2 >= l && n2 <= r))    {         // Print the perfect square        Console.Write(n2 + " ");         // Get the next perfect square        n2 = n2 + number;         // Next odd number to be added        number += 2;    }} // Driver codepublic static void Main(String[] args){    int l = 2, r = 24;     perfectSquares(l, r);}} // This code is contributed by Rajput Ji
<script>// Javascript implementation of the approach // Function to print all the perfect// squares from the given rangefunction perfectSquares(l, r){     // Getting the very first number    let number = Math.ceil(Math.sqrt(l));     // First number's square    let n2 = number * number;     // Next number is at the difference of    number = (number * 2) + 1;     // While the perfect squares    // are from the range    while ((n2 >= l && n2 <= r)) {         // Print the perfect square        document.write(n2 + " ");         // Get the next perfect square        n2 = n2 + number;         // Next odd number to be added        number += 2;    }} // Driver codelet l = 2, r = 24; perfectSquares(l, r); // This code is contributed by subhammahato348</script>
4 9 16
 
mohit kumar 29
jit_t
ankthon
29AjayKumar
Rajput-Ji
sravankumar8128
subhammahato348
maths-perfect-square
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion