Skip to content

Commit 4dbd283

Browse files
bilalcancodeabranhe
authored andcommitted
Update prime.cpp
We can find the prime number by running only to the half of the number entered. In this way the running time can be decreased. Also we can use bool variable to keep track of prime number rather than integer which is more memory efficient
1 parent 4fa4988 commit 4dbd283

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

algorithms/math/prime.cpp

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
#include<iostream>
22
using namespace std;
3-
int main()
4-
{int n,flag;
5-
cin>>n;
6-
//to check whether a number is prime or not
7-
for(int i=2;i<n;i++){
8-
if(n%i==0)
9-
flag++;}
10-
if(flag>0)
11-
cout<<"number is not prime"<<endl;
12-
else cout<<"number is prime"<<endl;
3+
int main(){
4+
int n;
5+
cin>>n;
6+
//to check whether a number is prime or not
7+
bool isPrime=true;
8+
for(int i = 2 ;i <= n/2; i++){
9+
if( n%i == 0){
10+
isPrime=false;
11+
break;
12+
}
13+
}
14+
if(isPrime) cout<<"Number is Prime"<<endl;
15+
else cout<<"Number is not prime"<<endl;
1316
return 0;
1417
}

0 commit comments

Comments
 (0)