btw i found out the answer i couldn't find anywhere not in this forum, not elsewhere, this look like this, the tricky part, which actually HAS to be used to find prime numbers is if (!(i%j)&&(i!=j))
#include <iostream>
usingnamespace std;
int main()
{
int b;
bool prime;
cout<<"write the number "<<endl;
cin>>b;
for (int i = 1; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j))
{
prime = false;
break;
}
if (j==i)
{prime = true;}
}
if ( prime ){ cout << i <<"is prime" << endl;}
else {cout << i << " is not prime" << endl;}
}
system("pause");
return 0;
}
Problem is that you are checking at least double the numbers you need to. You only need to check to the square root of the number. Anything after that, you're just double checking your previous numbers.
@MiiNiPaa
I don't program in C++ to necessitate a paid upgrade, and I want to avoid breaking the law if I can.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int b;
bool prime;
cout<<"write the number "<<endl;
cin>>b;
for (int i = 1; i <= b; i++)
{
prime = (i>1); // set to true for numbers except 1
for (int j = 2; j < i; j++)
{
if (!(i%j))
{
prime = false;
break;
}
}
if ( prime )
cout << i << " is prime" << endl;
else
cout << i << " is not prime" << endl;
}
system("pause");
return 0;
}
... and as has been pointed out, even going as far as i-1 in the loop is doing too many iterations.