Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algo gets the timeout for the Integer.MAX_VALUE

I have an algorithm that provides the factors of an integer from the 1 to N. The code is provided below,

public static int solution(int N) {

        int count = 0;

        for (int i = 1; (i * i) <= N; i++) {

            if (i * i == N) {
                count++;

                return count;
            }

            if (N % i == 0) {
                count += 2;
            }
        }

        return count;
    }

This works fine, but, obviously breaks for the very large value of the integer, for example, Integer.MAX_VALUE. How do I improve the code for the VERY large value?

like image 292
Heisenberg Avatar asked May 27 '26 20:05

Heisenberg


1 Answers

Just change your for loop condition as below and it should work.

 for (int i = 1; (i * i) > 0 && (i * i) <= N; i++) {

This change is needed because of the overflow that occurs at 46341 and any square from this number results in a negative value(most likely, as overflow is an undefined behaviour) and results in satisfying the condition of (i * i) <= N and the loop continues further. So, just add an additional check that the square should be > 0 to handle such case.

like image 87
nice_dev Avatar answered May 30 '26 11:05

nice_dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!