Find prime numbers between random numbers

Pages: 12
Does Visual Studio 2008 have C++ 11 support? I don't think it does.
Compiler released in 2008 cannot support standard from 2011. May I ask why not upgrade to VS 2012/13?
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))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <iostream>
using namespace 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;
}
Last edited on
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.
While you are correct, the are other ways to implement that requirement. Usually the loop is set to finish before j is equal to i.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstdlib>
using namespace 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.
Last edited on
GRex2595 wrote:
I don't program in C++ to necessitate a paid upgrade,
VS2013 Express is free
Topic archived. No new replies allowed.
Pages: 12