Which one of these two code samples are supposed to be faster?

Viewed 49

I was scrolling through edabit doing some of their challenges when I stumbled across one where you were to return the amount of prime numbers under the passed value. I completed the challenge and wanted to check if my solution was quicker than most others, so I checked one and found out that my code, according to the program at least, was slower even though mine is supposed to do fewer checks.

Here is the code I wrote:

public static int test1(int num) {
    int primes = 0;
    for(int i = 3; i<=num; i+=2) {
        boolean prime = true;
        for(int j =  (int) Math.sqrt(i); j>1; j--) {
            if(i%j==0) {
                prime = false;
                break;
            }
        }
        if(prime == true) primes++;
    }
    return (num >= 2 ? primes+1 : 0);
}

and here is the other one:

public static int test2(int num) {
    int result = 0;
    for (int i = 2; i <= num; i++) {
        int count = 0;
        for (int j = 1; j <= i; j++){
            if (i % j == 0){
                count++;
            }
        }
        if (count == 2){
            result++;
        }
    }
    return result;
}

By a quick look over you can see that mine is almost the same as the other code sample but optimized as it is supposed to do fewer checks as the number of times it will loop is less. However, that is apparently not the case. Could someone please tell me why my code would not be running as fast or faster than the other code sample? I only tested values between 1 and 150 in case that information is useful.

0 Answers
Related