Test case for input 2 is incorrect?


  • -2
    S

    The code works fine and I have used this to get prime numbers upto a 10Mil (though it takes a while), but the test case here fails when it checks 2. The test case says the expected number is 0 when 2 is the input.

    Code:

    public int countPrimes(int n) {

        int count = 1;
    	int flag = 0;
    	if(n < 2)
    		return 0;
    	for(int i = 3;i<=n; i= i+2){
    		
    		flag = 0;
    		for(int j = 3; j*j <= i ; j =j+2){
    			if(i%j == 0){
    				flag = 1;
    				break;
    			}
    		}
    		if(flag == 0)
    			count ++;
    	}
    	return count;
    }

  • 0

    0 is what should be returned when n = 2. Notice that it is saying "less than" n, instead of less than or equal to n.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.