+ 1
What is the problem of this code and why its output is not what i demanded? Why it repeats 4 times the prime number or not prime
#include <iostream> using namespace std; int main() { int i,n; cout <<"enter a number:"; cin >>n; for (i=1;i<=n/2;i++) {if (n%i==0) cout<<"n is not a prime number"; else cout <<"n is a prime number"; } return 0; }
3 Respuestas
+ 4
If i got right u wanna make a c++ program for prime numbers...
For it juat run a for loop from two upto n /2 and it will check that whether the number is prime of not and if prime then it must be divided somewhere else between otherwise it will be not divided by any other number between 2 and n/2 ..
And check with the help of a flag that if the flag got changed due to number being divided by some i in the loop then cout not prime otherwise prime...
Specially for 1 check initially and cout not prime...
In ur program u r just checking the inout number to be divided by any number from 1 to n/2 and thus its obvious it will be divided by 1 and maybe my other numbers too in between but it sometimes also not gets divided so prints not prime and this happens again and again as the loop runs.. That's why multiple outputs..
+ 3
For a prime number program u must do something like this :
int main()
{
int n, i ;
cin>>n;
if(n==1)
cout<<"not a prime number" ;
int flag = 1;
for ( int i = 2; i <n/2; i++)
{
if(n%i==0)
flag =1;
}
if(flag == 1)
cout <<"not a prime number" ;
else cout<<" a prime number" ;°
return 0;
}
Hope it helps 😅
0
#include <iostream>
using namespace std;
int main() {
int i,n,count;
cout <<"enter a number:";
cin >>n;
for (i=1;i<=n;i++){
if(n%i==0)
count++;
}
if (count == 2)
cout<< n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}
A number is prime if it is only divisible by 1 and the number itself. So you need to check that using a count variable.