I made a program that returns the sum of all primes less than 2 million. I really don’t know what is happening with this, I get 142891895587 as my answer when the correct answer is 142913828922. It seems that it lacks some prime numbers. I am sure that the getPrime function works as intended. I used it a couple of times earlier and worked correctly than. The code is as follows:
vector<int> getPrimes(int number); int main() { unsigned long int sum = 0; vector<int> primes = getPrimes(2000000); for(int i = 0; i < primes.size(); i++) { sum += primes[i]; } cout << sum; return 0; } vector<int> getPrimes(int number) { vector<bool> sieve(number+1,false); vector<int> primes; sieve[0] = true; sieve[1] = true; for(int i = 2; i <= number; i++) { if(sieve[i]==false) { primes.push_back(i); unsigned long int temp = i*i; while(temp <= number) { sieve[temp] = true; temp = temp + i; } } } return primes; }
The expression i*ioverflows because it iis int. It is truncated before the appointment temp. To avoid overflow, make him static_cast<unsigned long>( i ) * i.
i*i
i
int
temp
static_cast<unsigned long>( i ) * i
, : for(int i = 2; i*i <= number; i++).
for(int i = 2; i*i <= number; i++)
.
, (un) , , : int , §4.7/2, .
, : http://en.wikipedia.org/wiki/Long_integer.
:
unsigned long int temp = i*i;
. , temp. sieve? i, ? , , ?
sieve
, , . - . 2 , , , 30. , . , .
. - , .
. , getPrimes , . ( , - .)
getPrimes
64- . :
unsigned long int temp = i * i;
, int, int (32-). :
unsigned long int temp = (unsigned long int) i * i;
My system has a long 32-bit, so I had to change both temp, and sumto unsigned long long.
sum
unsigned long long
Source: https://habr.com/ru/post/1744726/More articles:.toggle (true) throw null in $ (document) .ready (function ()) - jqueryКак ограничить количество одного и того же действия в стеке для приложения для Android - androidNaming convention for primary key in table - cakephpHow can I do such a typical unittest? - pythonEmail Functionality for Public Website - htmlScala internal compilation. Working with interactive.Global - scalaHow to get the file size of a large (> 4 GB) file? - cwhat buffer size is best for uploading a file to the Internet - httpdo not display notification after seeing that once - androidMvcContrib CheckBoxList - mvccontribAll Articles