Chaklader Asfak Arefe :
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?
vivek_23 :
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.