0

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++; } ; } 
4
  • 1
    The right tool for investigating this is a debugger. Commented Oct 22, 2017 at 3:39
  • 6
    You execute n % i with i == 0 Commented Oct 22, 2017 at 3:40
  • start at i=1 instead Commented Oct 22, 2017 at 3:44
  • 1
    start with n % i with i = 2 Commented Oct 22, 2017 at 3:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.