Sign in
Log inSign up

Why do both of these programs behave the same?

Indu Pillai's photo
Indu Pillai
·Aug 29, 2017

The following two C++ programs give the same result, but when I benchmarked them for a very high figure (something like in millions), the difference was too much, the second program was very efficient.

There difference is in the nested loop, in the first one it's int j=2; j<i; j++ and in the second one it's int j=2; j*j<i; j++

Program # 1:

#include <iostream>
using namespace std;

int main () {
    for (int i=200; i<400; i++) {
        bool prime=true;
        for (int j=2; j<i; j++) {
            if (i % j == 0) {
                prime=false;
                break;    
            }
        }   
        if(prime == true){ cout << i << "\n"; }
    }
    return 0;
}

Program # 2

#include <iostream>
using namespace std;

int main () {
    for (int i=200; i<400; i++) {
        bool prime=true;
        for (int j=2; j*j<i; j++) {
            if (i % j == 0) {
                prime=false;
                break;    
            }
        }   
        if(prime == true){ cout << i << "\n"; }
    }
    return 0;
}