see code, question after.
#include <iostream>
#include <cstdio>
bool prime(unsigned long long num);
int main(){
unsigned long long temp;
unsigned long long max = 600851475143;
FILE * fptr;
try{
fptr = fopen("primes.txt","w");
#pragma omp parallel for
for(unsigned long long i = 2; i<max;i++){
if(prime(i)){
temp = i;
fputs(i + ",",fptr);
//int percent = (int)((float)i)/((float)max);
//if(percent > 1 && (percent % 10 == 0)){
// std::cout << "Percent Complete: " << percent << std::endl;
//}
}
}
std::cout << temp << std::endl;
fclose(fptr);
}catch(...){
std::cout << "Exception!" << std::endl;
}
return 0;
}
bool prime(unsigned long long num){
for(unsigned long long i = 2;i<num;i++){
if(num%i == 0)
return false;
}
return true;
}
@gw runtime failure:
runtime failure:
time failure:
me failure:
ailure:
:
tualQuery failed for %d bytes at address %pQuery failed for %d bytes at address %pery failed
for %d bytes at address %pfailed for %d bytes at address %p for %d bytes at address %pd
bytes at address %pbytes at address %pat address %pddress %press %ppnown pseudo relocation
protocol version %d.
udo relocation protocol version %d.
relocation protocol version %d.
location protocol version %d.
tion protocol version %d.
on protocol version %d.
rotocol version %d.
n %d.
.
Unknown pseudo relocation bit size %d.
nknown pseudo relocation bit size %d.
udo relocation bit size %d.
o relocation bit size %d.
cation bit size %d.
bit size %d.
Why is this runtime failure happening? I’m guessing it has something to do with unsigned long long but I have no idea. Also tried without the omp directive and still same problem.
You made a mistake here:
fputs gets const char* as a first argument. You add integer value ‘i’ to a const char* “,” value. This expression i+”,” will point to an invalid memory block as soon as ‘i’ becomes larger then 0 since there is no overloaded operator ‘+’ in C++ which concatenates an integer with a const pointer to a char buffer
You may use the sprintf function instead:
or, simply fprintf which will put write the string directly to the file
Also, I suggest you to close the file handle outside of the try{ .. }catch block. Otherwise, in case of exception, your file will not be closed at all