What is the problem in the code here to print prime number?

https://ide.geeksforgeeks.org/online-cpp-compiler/c175084a-a1e9-4c09-a13a-f9ebbd153ab3

Mistakes:

  1. at line No. 18 : you are printing “prime” without dividing all number in b/w 2 to n

For example: n=9
for(i=2) ==> 9%2 != 0 ==> print prime
for(i=3) ===> 9%3 == 0 ===> print not prime
for(i=4) ==> 9%4 != =0 ==> print prime…so on…

so your code is not dividing to all numbers in [2,n] before concluding the number is prime or not…

  1. at line No. 14:
    instead of printing 'not prime" if n divides i,
    what you need to do is ==> after ensuring the number is not prime than break the loop…

Correct Modified Code is:

int main(){
int n;cin>>n;
bool isprime=true;
for(int i=2;i<n;i++){
     if(n%i == 0){
          isprime=false;
          break;
     }
}
if(isprime==true){
      cout<< "number is Prime"<<endl;
}else{
      cout<<"number is Not Prime"<<endl;
}
  return 0;
}

I hope this helps if you have further doubt feel free to ask