To check whether a number is prime or not in c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
I did not understood this program
/*program to check whether a no is prime or not prime*/
#include<iostream.h>
#include<conio.h>
void main()
{int n,i=2,j=1;
cout<<"enter a no";
cin>>n;
while((i<n/2) &&(j==1))
{if(n%i==0)
j=0;
i++;
}
if(j==1)
cout<<endl<<"no is prime";
else
cout<<"no is not prime";
getch();
}
I will try to rewrite it. Maybe it wiil be more readable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include   <iostream>
#include   <conio.h>

using namespace std;

int main()
{
   unsigned int number;

   cout << "Enter a number: ";
   cin >> number;

   bool prime = true;

   for ( unsigned int i = 2; i < number / 2; i++ )
   {
      if ( number % i == 0 ) prime = false, break;
   }

   if ( prime ) cout << "Number " << number << " is prime\n";
   else cout << "Number " << number << " is not prime\n";

   getch();

   return ( 0 );
}


If a number is divisible by another number ( number % i == 0 ) then it is not a prime number.
Last edited on
Topic archived. No new replies allowed.