views:

158

answers:

2

How would I change this loop to print prime number in reverse... starting from the biggest one first

int main(){

    bool prime;
    for( int i=3; i<=10000; i++){
        prime = true;
        for(int n=2; n<=i-1; n++){
            if( i%n == 0){
                prime = false;
            }
        }
        if(prime){
            cout << i << " ";
        }
    }
    return 0;

}
+12  A: 

You can reverse the for loop as follows:

for( int i=10000; i>=3; i--) {

That being said - you can also simplify this. You only need to check until you reach the square root of the number. Also make sure that, when you find that a number isn't prime, you break out immediately:

int main() {

    bool prime;
    for( int i=10000; i>=3; i--) {
        prime = true;
        int max = sqrt(i)+1; // Don't check beyond this...
        for(int n=2; n<=max; n++)
        {
            if( i%n == 0){
                prime = false;
                break; // This prevents you from continually checking!
            }
        }
        if(prime){
            cout << i << " ";
        }
    }
    return 0;
}
Reed Copsey
+1  A: 

Just reverse the direction of the outer for-loop.

int main()
{
    bool prime;
    for( int i=10000; i>=3; --i)
    {
        prime = true;
        for(int n=2; n<=i-1; n++)
        {
            if( i%n == 0)
            {
                prime = false;
            }
        }
        if(prime)
        {
            cout << i << " ";
        }
    }
    return 0;
}
abelenky