简体   繁体   中英

How can I reduce iterations in for loop that takes to much time for execution?

Here, I am finding number of perfect square numbers in given range.

But I am dealing with 'for' loop execution that takes much time for execution.

The index/key traverses from two numbers, lets say A to B, and does some operation in for loop.

The problem arises when there's large difference between A and B (eg A = 2 & B = 100000)

Can u suggest how can I reduce or optimize the execution time?

        Scanner in = new Scanner(System.in);
        int A = in.nextInt();
        int B = in.nextInt();

        int cnt = 0;
        for(int number =A ; number<= B; number++){
        int sqrt = (int) Math.sqrt(number);
              if(sqrt*sqrt == number) {
                    cnt++;
                }
        }
        System.out.println(cnt);

Or is it because of Math class operations that takes too much time to execute?

Can you suggest any alternate approach to find the square numbers between given range?

Thanks in advance!

I found an alternate way to find the count of perfect square numbers between given range.

This can be simply achieve by using Math.floor and Math.ceil operations.

Math.floor(Math.sqrt(B)) -  Math.ceil(Math.sqrt(A)) + 1

Thanks! :)

Instead of going through each number in the range and figuring out if its a perfect square, I would suggest the below

Find a square root of the start number and find the integer part of it.

Lets say start number is 5. So integer part of the square root will be 2.

Now do the same for the range end number

Lets say end range was 1000, so the integer part of its square root would be 31. Now iterate from 2+1 to 31 and keep printing its square. That would give you the perfect squares between the given range.

Instead of the if(sqrt * sqrt == number) you could also check whether the double returned by Math.srt(number) is a integer. The algorithm would than become as follows:

for(int number =A ; number<= B; number++){
    if((Math.sqrt(number) % 1) == 0) {
        cnt++;
    }
}

Note: Haven't tried the code myself so might not work as I expect.

Regarding the question on how you can improve the performance. The checking on whether the number is perfect could be done in parallel by executing per number a task. The access to the counter has to be synchronized than, (to be on the safe side).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM