function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ritik DwivediRitik Dwivedi 

This is the apex code (with result)for calculating no of perfect squares between given range . how to get total no of perfect square (in numbers) here is 6. i am unable to find please solve my problem

//Apex Programme to find the perfect squares between two numbers

public class PerfectSquare {
    public static void  perfectSqMethod(integer in1,integer in2){
        
        // For every element from the range between in1 and in2
          
        for(Integer i = in1; i<in2; i++){
                       
        double d1 = Math.sqrt(i);
        double d2 = math.round(d1);
            
        // If current number  is a perfect square 
        if (d1==d2) 
        system.debug(i);
    } 
                                      
                    
    }   
}

//calling method 
PerfectSquare.perfectSqMethod(10,100);
           
     

//Result
16
25
36
49
64
81
SwethaSwetha (Salesforce Developers) 
HI Ritik,
The below article gives an idea of the algorithm(logic) . You will need to customize according to your requirement

https://stackoverflow.com/questions/29057462/how-to-find-number-of-perfect-squares-in-the-given-range#:~:text=There%20is%20a%20trick.,add%201%20to%20the%20difference.

Hope this helps you.Thanks
ANUTEJANUTEJ (Salesforce Developers) 
Hi Ritik,

You could try using the code as below for finding the number of perfect squares and printing the squares:

public class ParkLocator {

    public void countSquares(integer a, integer b) 

    integer cnt = 0; // Initialize result 

    // Traverse through all numbers 
    for (integer i = a; i <=b b; i++) 

        // Check if current number 'i' is perfect 
        // square 
        for (integer j = 1; j * j <= i; j++) 
            if (j * j == i) 
            {system.debug(j*j);
            cnt++;}
  

    system.debug('cnt->'+cnt);
}

}


This would be returning the number of perfect squares between given two numbers including the last number.

I hope this helps.

Regards,
Anutej