Question

look , that code above is for calculate the sum of the prime numbers below 2000000 , but its not giving the correct answer but when i try to sum the prime numbers below 10, or 20 its gave the right answer , can anyone help me to discover whats is going on!?

#include <stdio.h>
#include <math.h>

int main(){

    unsigned int ref = 0, m,divisoes = 0 , total = 0,flag = 2;
    unsigned int soma =0;

    while(ref < 9999999999999){
        ref = (flag * 2)-1;
        m = ceil(sqrt(ref));
        while( m > 2){
            if(ref % m == 0)
                divisoes++;
            m--;            
        }
        if(divisoes == 0){
            if( ref > 2000000) // limitador
             break;
            printf("%d \n",ref);
            soma += ref;
            total ++;
        }
        divisoes = 0;
        flag ++;    
    }
    // somando mais 2 , por que dois é o unico numero primo par.
    soma +=2;
    total++;
    printf("Soma %d , Total de Primos %d",soma,total);
    return 0;


}
Was it helpful?

Solution

9999999999999 is quite a bit larger than the maximum value of unsigned int (2^32 - 1). A simple fix could be to add ULL suffix to all literals and switch unsigned int to unsigned long long.

OTHER TIPS

Numeric data types have a certain amount of storage in memory to work with, after a certain value they overflow.

You can think of this as an odometer on a car rolling over after it hits too many miles. You can use a larger data type and it might support your needs. At some point numbers get large enough you need a library for arbitrary length numbers. Googling 'c++ BigInteger' will yield good results for you.

The int datatype can store only (2^32-1) and your number is bigger then that... Use unsigned long so it can store long numbers. . You van also use unsigned float or unsigned double for big floating point values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top