i have got a quizz to write a programm that gives the sum of all even
numbers between two variables x and y and then displays the sum.
Include both x and y in the total sum.
Any one here can help me............ ?
Well the dullards in your class will doubtless
furnish an algorithmic solution using something
called a 'loop'.
The brighter students will realise that there is
an analytic solution, and write a program to
calculate this directly.
However, since you are in a C++ class I feel
confident that your professor will settle for
nothing short of a compile-time solution using
metaprogramming that spits out the answer in
an error message - let's face it, you can't beat
a program for speed that doesn't even produce
an .exe, as I'm sure you'll agree.
Type the code below into a file called metasum.cpp
and then eg for x=5 and y=20, compile the code like
this:
cl /c metasum.cpp -Dx=5 -Dy=20
The first part of the error message will give
you the answer to the problem (here, 109):
metasum.cpp
metasum.cpp(10) : error C2079: 'ans' uses
undefined struct 'the_answer_is<__formal>'
with
[
__formal=109
]
:
If this doesn't get you an A then there's something
very wrong with all of us.
<code>
typedef unsigned int u;
template<u> struct the_answer_is;
template<u a, u b, u c >
struct sx {
sx() {
the_answer_is<(b/2+1)*(b/2)-(a/2-1)*(a/2)+c>
ans;
}
};
template<u a, u b, u aa, u bb> struct s;
template<u a, u b>
struct s<a,b,0,0> : sx<a,b,0> {
s() : sx<a,b,0>() {}
};
template<u a, u b>
struct s<a,b,0,1> : sx<a,b-1,b> {
s() : sx<a,b-1,b>() {}
};
template<u a, u b>
struct s<a,b,1,0> : sx<a+1,b,a> {
s() : sx<a+1,b,a>() {}
};
template<u a, u b>
struct s<a,b,1,1> : sx<a+1,b-1,a+b> {
s() : sx<a+1,b-1,a+b>() {}
};
template <u a, u b>
struct sum : s<a, b, a%2, b%2> {};
sum<x,y> eval;
</code>