Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
public class Solution {
    public int countPrimes(int n) {
        if(n == 0){
            return 0;
        }
        int count = 0;
        for(int i = 2; i <= n; i++){
            if(!(n % i == 0)){
                count++;
            }
        }
        return count;
    }
}


What I have tried:

There are several cases that work for my code, but not all of them. For example, when n is assigned to 4, it doesn't count the two since 4 % 2 == 0. How can I fix this issue for not only this case but other cases as well?
Posted
Updated 6-Aug-16 7:37am
v2

1 solution

Quote:
How can I improve my counting prime numbers function?
there is nothing to improve, because what you have done is not working.
the whole logic of your code is to be reviewed.
Your logic actually say that i is a prime if not a divisor of n, it is plain wrong.
You need to create a function that tells you if a number is a prime and change your code to:
Java
public int countPrimes(int n) {
    if(n == 0){
        return 0;
    }
    int count = 0;
    for(int i = 2; i <= n; i++){
        if(IsPrime( i )){
            count++;
        }
    }
    return count;
}
public int IsPrime(int n) {
    // here you have to check if n is a prime
}
 
Share this answer
 
Comments
EpicKai 6-Aug-16 13:42pm    
Ok, thank you. Yeah, I can see where my logic is wrong with my code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900