Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I can't seem to figure out exactly how to count the amount of prime numbers after a certain number.

What I have tried:

Java
public class Solution {
    public int countPrimes(int n) {
        if(n <= 2){
            return 0;
        } else if(n == 3){
            return 1;
        }
        int count = 0;
        for(int i = 2; i <= n; i++){
            if(IsPrime( i )){
                count++;
            }
        }
        return count;
    }
    public boolean IsPrime(int num) {
        for(int i=2;i<=num/2;i++){
            if(num % i == 0){
                return false;
            }
        }
        return true;
    }
}
Posted
Updated 6-Aug-16 9:08am
v2
Comments
Richard MacCutchan 7-Aug-16 2:34am    
What is the problem?

1 solution

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

What should be the result for n=0 or 1 ?
What should be the result for n=2 ?
Look at your code.
 
Share this answer
 
v2
Comments
Maciej Los 7-Aug-16 5:00am    
5ed!
Patrice T 7-Aug-16 5:07am    
Thank you

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