Reply to comment

Project Euler - Problem 1 - Sum All Integers Below 1000 and Divisible By 3 or 5

The first Project Euler problem is to calculate the sum of all integers below 1000 which are divisible by either 3 or 5.

My solution is implemented entirely in C++ templates. The value is recursively calculated at compile time. The template specialization struct Problem1<0> stops the recursion and returns 0.

To compile this code with gcc you must expand the maximum allowed template recursion depth to at least 1000.

g++ EulerProblem1.cpp -ftemplate-depth-1000

//EulerProblem1.cpp
#include <iostream>
 
template<int count>
struct Problem1
{
  static const int value = (((count % 3) == 0 || (count % 5) == 0)?count:0) + Problem1<count - 1>::value;
};
 
template<>
struct Problem1<0>
{
  static const int value = 0;
};
 
int main()
{
  std::cout << Problem1<999>::value << std::endl;
}

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.