Print all prime numbers between 2 and 100 - C++ Data Structure

C++ examples for Data Structure:Algorithm

Introduction

An integer is said to be prime if it's divisible by only 1 and itself.

Demo Code

#include <math.h>
#include <iostream>

bool isPrime(int);

int main(int argc, const char *argv[]) {
    for (int i = 2; i < 100; i++) {
        if (isPrime(i)) std::cout << i << " ";
    }//from  w ww. j  a v  a 2 s .  com
    std::cout << std::endl;

    return 0;
}
// determine whether n is prime
bool isPrime(int n) {
    if (n == 1 || n == 2) return true;

    // prime numbers cannot be even
    if (n % 2 == 0) return false;

    // upper limit sqrt as primes cannot be squared
    for (int i = 2; i < sqrt(n); ++i) {
        // has divisor not prime
        if (n % i == 0) return false;
    }
    return true;
}

Result


Related Tutorials