HELP writing code to check # if it is prime or not

This code allowed me to check if a number is a prime or not by outputting a 0 or a 1. My question, is how to get this code to not run when someone inputs 1 number but multiple. For example, after it check 4, it outputs 0 and the program is done. I want it to keep going.

#include <iostream>
using std::cin;
using std::cout;
using std;;endl;
#include <cmath>

int main(){
while (true){
int n;
cin>>n;
for (int k=2; k<=n-1; k++){
if (n%k==0){
cout<<"0"<<endl;
return (true);}
else if (n%k!=0){
cout<<"1"<<endl;
return (true);
break;}}
}
return 0;}
Last edited on
firstly, please do formatting with the [ code ] [ /code ] tags (no spaces near brackets).

Come up with an exit case -- for example, declare n outside the while loop and change while condition to while(n != -1) , so that you can enter -1 to exit.

In your "if" statements, you have two returns. Get rid of those -- the returns, since they're in the main() method, will exit the whole program. You only need the last return 0;

Consider also looking up an algorithm for checking prime (I think Euler has an easy one). You currently just check divisibility by two, and you're checking too many numbers.

gl
Topic archived. No new replies allowed.