Zum Hauptinhalt springen
  1. Blogs/

Suche nach den ersten hundert Primzahlen in C++

Daniel
Autor
Daniel
Engineer, Coder and Open-Source enthusiast.
Autor
Daniel

Suchen der Primzahlen kleiner 100 in C++.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// basic io
#include <iostream>
using namespace std;

int main ( int argc, const char* argv[] ) {

  int iCount   = 0;
  int iDivisor = 1;

  // loop over all natural numbers 
  for ( iCount = 1; iCount <= 100; ++iCount ){
    // state if current number is a prime number
    int iPrime = 1;

    // loop over each divisor candidate
    for ( iDivisor = 2; iDivisor < iCount; ++iDivisor ) {
      
      // if divisor matches the current number -> change state
      if ( iCount % iDivisor == 0 ){
        iPrime = 0;
      }
      
    }

    // if prime print to stdout
    if (iPrime == 1 ) {
      std::cout << iCount << std::endl;
    }
  }

  return 0;
}

Verwandte Artikel