C :: Aufgabe #275

1 Lösung Lösung öffentlich

Konsolenanwendung zur Bestimmung der Primzahlen - Ganzzahlenbereich

Anfänger - C von Labi1995 - 19.04.2020 um 20:39 Uhr
Schreiben Sie eine Konsolenanwendung zur Bestimmung der Primzahlen in dem vom Nutzer eingegebenen Ganzzahlenbereich von Null bis n unter Verwendung des Siebs des Eratosthenes.

Wie viele Primzahlen gibt es im Zahlenbereich bis 100?
Wie viele Primzahlen gibt es im Zahlenbereich bis 10.000?
Wie viele Primzahlen gibt es im Zahlenbereich bis 1.000.000?

Lösungen:

vote_ok
von kathleenw (3600 Punkte) - 29.06.2020 um 11:33 Uhr
Quellcode ausblenden C-Code
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>

bool istPrim(int zahl);

int main(void)
{
    int anzahl, i, bereich;
    anzahl = 0;
    
    printf("Bis zu welchen Bereich wollen sie wissen wieviele Primzahlen es gibt?(Wert größer als 1)");
    scanf("%d", &bereich);
    
    for(i=2; i<=bereich; i++) {
        if (istPrim(i)==true)
            anzahl++;
    }
    printf("Es gibt %d Primzahlen bis %d. \n", anzahl, bereich);
    
    anzahl = 0;
    for(i=2; i<=100; i++) {
        if (istPrim(i)==true)
            anzahl++;
    }
    printf("Es gibt %d Primzahlen bis 100. \n", anzahl);
    
    for(i=101; i<=10000; i++) {
        if (istPrim(i)==true)
            anzahl++;
    }
    printf("Es gibt %d Primzahlen bis 10000. \n", anzahl);
    
    for(i=10001; i<=1000000; i++) {
        if (istPrim(i)==true)
            anzahl++;
    }
    printf("Es gibt %d Primzahlen bis 1000000. \n", anzahl);
}


//prüfen ob es eine Primzahl ist
bool istPrim(int zahl) {
    bool prim, faktorgefunden;
    int t;
    
    if (zahl <= 2) {
        if (zahl < 2)
            prim = false;
        else
            prim = true;
    }
    else {
        if (zahl%2 == 0)
            faktorgefunden = true;
        else {
            faktorgefunden = false;
            t = 3;
            while (t*t <= zahl && faktorgefunden == false) {
                if (zahl % t == 0)
                    faktorgefunden = true;
                else
                    t=t+2;
            }
        }
    }
    
    if (faktorgefunden==false)
        prim = true;
    else
        prim = false;
    
    return prim;
}