开发者

Reversing a for loop... want to print numbers in reverse

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){
            cou开发者_如何学运维t << i << " ";
        }
    }
    return 0;

}


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;
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜