C++: Finding Prime Numbers

Finding a prime number is a big part of computing. Tons of homework assignments, programming exercises, contests, etc, have questions that require figuring out if a number is prime or print a list of primes in a certain range, etc… figured I’d post a simple way to figure out if a number is prime. This might not be the most “optimal” code but then again I wrote this first year in college and been reusing it ever since… enjoy.

This specific version was part of a loop and returned only the prime numbers.

int isPrime(int number){
    int count=0;
    for(int a = 1; a<=number ;a++)
        if(number % a == 0)
    if(count == 2)
        return number; 
    return 0; 

Leave a Reply

Your email address will not be published. Required fields are marked *