Template metaprogramming solution:
It is further assumed that the lower end of the range is 0.
template <int N> struct sum { static const int value = sum<N-1>::value + (N % 3 == 0 || N % 5 == 0 ? N : 0); }; template <> struct sum<0> { static const int value = 0; }; int main(int argc, char** argv) { int n = sum<999>::value; return 0; }
Below you can specify a range of numbers (for example, 0-999, 20-400). I am not a master of metaprogramming templates, so I could not come up with a cleaner solution (and I did it for my own benefit and practice).
template <int N, int Upper, bool IsLast> struct sum_range_helper { static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0) + sum_range_helper<N + 1, Upper, N + 1 == Upper>::value; }; template <int N, int Upper> struct sum_range_helper<N, Upper, true> { static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0); }; template <int Lower, int Upper> struct sum_range { static const int value = sum_range_helper<Lower, Upper, Lower == Upper>::value; }; int main(int argc, char** argv) { int n = sum_range<0, 999>::value; return 0; }
Marlon
source share