Home > Net >  Getting no output on console for big iteration without any error message
Getting no output on console for big iteration without any error message

Time:01-09

int main() {
    int naturalNumber = 2;
    int divider = 0;
    int rest = 1;
    long long int sumOfPrimes = 0;
    while (naturalNumber <= 2000000) {
        divider = naturalNumber;
        while (rest != 0) {
            divider--;
            rest = naturalNumber % divider;
        }
        rest = 1;
        if (divider == 1) {
            sumOfPrimes = sumOfPrimes   naturalNumber;
        }
        naturalNumber  ;
    }
    std::cout << sumOfPrimes;
}

Howcome does the sum output not appear on the Console after I set the loop condition to go through 2million iterations. And I don't get any error message. It works when it's set to less than ~100'000 iterations. Is this a memory issue or something else?

I was trying to calculate a sum of all primenumbers below 2 million through iteration.

CodePudding user response:

This is a very inefficient way to calculate a series of prime numbers, so the most likely answer is that it's just taking a very very long time.

If you know you need all of the primes up to 2,000,000, the Sieve of Eratosthenes is your friend.

Something like:

int n = 2000000;
std::vector<bool> is_prime(n 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i  ) {
    if (is_prime[i] && (long long)i * i <= n) {
        for (int j = i * i; j <= n; j  = i)
            is_prime[j] = false;
    }
}

long long int sum_primes = 0;
for (int i = 0; i < n; i  ) {
    if (is_prime[i]) sum_primes  = i;
}

This runs in O(n) complexity, vs. O(n^2).

  • Related