#include <vector>
#include <cmath>
void print(std::vector <int> const& a) {
for (int i = 0; i < a.size(); i ) {
std::cout << a.at(i) << " ";
}
}
std::vector<int> factors(int n) {
std::vector<int> vec = {};
for (int i = 0; i < round(sqrt(n)); i ) {
if (size(factors(i)) == 0) {
vec.push_back(i);
}
std::cout << i;
}
return vec;
}
int main() {
std::vector<int> vec = factors(600851475143);
print(vec);
}
This is my C code for Project Euler #3.
New to C , so my code might be completely wrong syntactically, however I am not getting any build errors (using Visual Studio).
Not getting any output however. I understand this could be my fault, and the program might just be running extremely slow. But I programmed this in python using the same iterative method and it worked perfectly with a fast runtime.
Edit:
I am however getting this message in the console:
D:\RANDOM PROGRAMMING STUFF\PROJECTEULER\c \projecteuler3\x64\Debug\projecteuler3.exe (process 13552) exited with code 0.
Press any key to close this window . . .
CodePudding user response:
If you enable your compiler warnings, you should see an overflow warning
prog.cc: In function 'int main()': prog.cc:23:36: warning: overflow in conversion from 'long int' to 'int' changes value from '600851475143' to '-443946297' [-Woverflow] 23 | std::vector vec = factors(600851475143);
so what gets passed to factors
is not 600851475143
but -443946297
CodePudding user response:
Of course Gaurav has given the correct answer. This is how to fix it, change from int to unsigned long long, to allow for the biggest integers possible that are supported without any external libraries
#include <cmath>
#include <iostream>
#include <vector>
void print(std::vector<int> const& list){
for( auto const& item : list){
std::cout << item << "\n";
}
}
std::vector<int> factors(unsigned long long n) {
std::vector<int> vec = {};
for( int i = 0; i < std::round(std::sqrt(n)); i ){
if( factors(i).empty() ) {
vec.push_back(i);
}
//std::cout << i << ", ";
}
return vec;
}
int main() {
std::vector<int> vec = factors(600851475143ULL);
print(vec);
}
I have also done some other minor changes:
- Change the foor loop of print to a rang-based for loop
- Added a delimeter i printing
- added std:: namespace to functions
- replaced size(vec) == 0 with empty to improve readability
Another good habit is to compile with -Wall
to enable more warnings and -Werror
so you are actually forced to take care of all warnings instead of brushing them off.