Is my compiler broken? (includes template metaprogramming)
Hey all, so I was just recently shown the site, Project Euler and decided to play around with some of the problems.
On problem 5 I decided to brute force the answer. Here is my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
using namespace std;
template<int upto>
inline bool isDivisible(unsigned int a) {
bool ret = true;
int val = upto;
while (ret == true && val > 0) {
ret = (a % val == 0);
--val;
}
return ret;
}
int main(int argc, char* argv[]) {
bool found = false;
unsigned int start = 20;
while (!found) {
found = isDivisible<20>(start);
++start;
}
cout << start << endl;
cin.ignore();
return 0;
}
|
After running this code for ~20 seconds the result output is: 232792561 which is obviously incorrect.
I'm using Visual C++ Express 2010 from Microsoft and out of curiosity, I changed the value 'start' to 232792561 but then my output became 465585121.
Any help here would be greatly appreciated.
EDIT: gcc produced the same results.
EDIT2: removed template metaprogramming and received same results.
EDIT3: just changed ++start to start += 20 to speed it up but then got the number 232792580 which is also incorrect.
Last edited on
If you initialize start with the value 21 you'll find the correct result.
Well, the correct answer is 232792560 but I'm not really sure what you need to tweak to get it...
Ok, try putting
++start;
above
found = isDivisible<20>(start);
Or better, try this:
1 2 3 4
|
while (true) {
if (isDivisible<20>(start)) break;
++start;
}
|
Last edited on
Stepping through it with a debugger shows that there are problems with your logic, not the compiler.
-_- now I know why they tell you to get a goooood nights sleep. Thanks :)
Last edited on
Topic archived. No new replies allowed.