Nidal EL FENGAOUI
Nidal EL FENGAOUI

Reputation: 1

Print all prime number lower than n in C++ ( file crash )

I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.

#include <iostream>

using namespace std;

bool premier(int x) {
    int i = 2;
    while (i < x) {
        if (x % i == 0)
            return false;
        i++;
    }
    return true;
}

int main() {
    int n;
    int i = 0;
    cout << "entrer un entier n : ";
    cin >> n;
    while (i < n) {
        if (n % i == 0 && premier(i))
            cout << i;
        i++;
    }
    ;
}

Upvotes: 0

Views: 921

Answers (1)

J...S
J...S

Reputation: 5207

As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.

You want to print all prime numbers less than n and has a function to check primality already.

Just

while (i < n){
    if (  premier(i) == true ) 
        cout<<i;
    i++;
}

And while printing, add a some character to separate the numbers inorder to be able to distinguish them like

cout<<i<<endl;

P.S: I think you call this a C++ program. Not a script.

Edit: This might interest you.

Upvotes: 1

Related Questions