#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
cout << "Enter the no. and we will tell you whether it's Prime or Non-Prime \n";
cin >> n;
for (int i=2; i<n; i++) {
if (n%i== 0){
cout << "Non-Prime"<< endl;
break;
}
else {
cout << "Prime" << endl;
} break;
}
return 0;
}
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
cout << "Enter the no. and we will tell you whether it's Prime or Non-Prime \n";
cin >> n;
bool flag=0;
for (int i=2; i<=sqrt(n); i++) {
if (n%i== 0){
cout << "Non-Prime"<< endl;
flag=1;
break;
}
}
if (flag ==0) {
cout << "Prime" << endl;
}
I wrote two pieces of code, simpler one is mine but the other second one having square root function involved was from internet. I want to program a simple code telling me whether a number is prime or not, so please tell me though both pieces of code do the same work what is logic in the second code and is it really necessary to write it in that way?