0
Source code to check prime no is not working..need assistance in this regard...
#include <iostream> using namespace std; int main() { int num ; int flag=0 int i=2; cout<<"enter no"; cin>>num; while (i< num) { if(num%i==0) { flag=1; break; } i++; } else if(flag==0) cout>>"prime no"; } { else cout<<"not prime"; } return 0; }
6 Respostas
+ 3
Like I mentioned in my earlier post, your code would say every integer less than 2 is prime, including 0 and 1. But none of them are. To fix this, just add the following before your while loop.
if (num < 2) {
flag = 1;
}
+ 3
You wrote a ">>" instead of "<<" and had some braces in the wrong places. Here's a fixed code:
#include <iostream>
using namespace std;
int main()
{
int num ;
int flag = 0;
int i = 2;
cout << "enter no: ";
cin >> num;
while (i < num) {
if (num % i == 0) {
flag = 1;
break;
}
i++;
}
if (flag == 0) {
cout << "prime no";
}
else {
cout << "not prime";
}
return 0;
}
Note: I didn't change your logic, and currently it would say that all the integers smaller than 2 are primes, whereas none of them are. So you'd need to add an extra if condition for that.
+ 2
You're welcome, Usman! :)
+ 1
hmmm...
its start working...😊
thanks alot sir👍👍
0
it shows o/p compilation error
0
//its working but when i enterd 0 it
//shows prime no but 0 is not
//prime no..how can i make changes
#include <iostream>
using namespace std;
int main()
{
int num ;
int flag;
flag=0;
int i;
i=2;
cout<<"enter no\n";
cin>>num;
while (i< num) {
if(num%i==0)
{
flag=1;
break;
}
i++;
}
if(flag==0)
{
cout<<"prime no="<<num;
}
else
{
cout<<"not prime: \n "<<num;
}
return 0;
}