Trying to learn c++. Why does this seg fault at 9 million but not at 2 million?#include <iostream>
long prime(int n) {
std::cout << "starting\n";
bool primes[++n];
for (int i = 0; i < n; i++) {
primes[i] = false;
}
for (int p = 2; p < n; p++) {
if (!primes[p])
for (int j = p * 2; j < n; j += p)
primes[j] = true;
}
long sum = 0;
for (int i = 0; i < n; i++)
if (!primes[i]) sum += i;
return sum;
}
int main() {
long primes = prime(9e6);
std::cout << primes;
return 0;
}
>>60031076
There is a reason interviewers only want you to sum the first two million primes.
i dont give a fuck about archaic shit like c(++) but maybe check ur types
Stack overflow perhaps? Try allocating that bitmap on the heap.
9million 32bit ints is 36megs so maybe a stackoverflow
>>60031076
> bool primes[++n];
>>60031123
>>60031143
Cool that got it.
>>60031160
Not correct? If you submit 20 it will only loop up to 19 with standard a < b syntax.
Creating the array with arr[++n] is correct then?
>>60031160
>>60031177
It creates the array of a fixed size?
Its too large an array
>>60031189
Actually I have no idea. The program works fine on random online compiler I pasted the code to.
Ok thanks everybody. Final question due to the lengths and the fact I am using a 64bit processor, should I use longs or ints?#include <iostream>
#include <math.h>
long prime(int n) {
std::cout << "starting\n";
bool *primes = new bool[++n];
for (long i = 0; i < sqrt(n) + 1; i++) {
primes[i] = false;
}
for (long p = 2; p < n; p++) {
if (!primes[p])
for (long j = p * 2; j < n; j += p)
primes[j] = true;
}
long sum = 0;
for (int i = 0; i < n; i++)
if (!primes[i])
sum += i;
return sum;
}
int main() {
long primes = prime(2e6);
std::cout << primes;
return 0;
}
>>60031217
Memleak, you noob. If you can't handle manual memory - use smart pointers.
auto primes = std::make_unique(new bool[++n]);
>>60031217
Use unsigned long, since unsigned int only goes up to 2^16 - 1 obviously. Has nothing to do with you having a 64bit processor.
>>60031217
I don't know about the C++ standard but the size of data types isn't really guaranteed. You should be using the data types from inttypes.h.
eg. uint64_t, uint32_t, int8_t