views:

207

answers:

6

hello i need program which returns sum of all even number <= to given n number
for example if n=even (let say 10) sum will be 2+4+6+8+10 or if n is odd (let say 13) 2+4+6+8+10+12 please help it should be recursive algorithm

i have done myself  
+2  A: 

Not that I like doing others' homework, but I'm interested whether I could solve that task quickly, so here's a C-like pseudocode which I haven't tested.

int evenSum( int number )
{
    if( number % 2 == 1 ) {
        return evenSum( number - 1 );
    }
    if( number == 0 ) {
        return 0;
    }
    return number + evenSum( number - 2 );
}
sharptooth
Sorry, this deserves a downvote. Solving other peoples’ homework = not cool.
Konrad Rudolph
@Konrad Rudolph: I know, but I found that challenging myself.
sharptooth
@Konrad, _you_ added the homework tag and, while you're probably right, I tend to prefer the view that people ask for what they want. If someone wants a solution, it is not my place to deny them. If they use it inappropriately, they'll either get caught out or they'll be zero threat to anyone in the workforce that isn't a lazy slob. If OP had specified homework, that would hav ebeen a different matter, but I'm only one organism in the swarm here - others may think differently.
paxdiablo
ok guys if u think that it is homework ok but one what i want to say is that i am creating problems myself no homework no such things i am trying to solve problems which i am creating and also thanks sharptooth my algorithm is the same
@davit-datuashvili: I suggest that next time you state a problem yourself and have a solution you're not sure of you ask the question in the following manner: "I tried to solve that-and-that problem and here's what I came with, but I'm not sure, will this work?"
sharptooth
@paxdiablo: Being a TA myself, I can only say that this attitude sucks. I’m not against providing help for homework (hey look! I did so myself!) but providing copypaste answers just supports antisocial behaviour. Rewarding such laziness (even the question is sloppy work, no effort has been put into at all)? Just wrong.
Konrad Rudolph
What does this pseudo-code return when given input 1 ?
High Performance Mark
@Konrad: I don't think we should ever downvote someone for giving a good answer to a question. Whether the question is homework or not, and the moral consequences of what the OP will do with the answer, are hardly sharptooth's responsibility. If you dislike the situation, I say downvote the *question*.
Joren
@High Performance Mark: It returns zero when given input 1.
sharptooth
@Joren: “the moral consequences of what the OP will do with the answer, are hardly sharptooth's responsibility” – is that so? I’ve made it clear in a previous comment that I don’t agree with that.
Konrad Rudolph
@Konrad Rudolph: IMO your basic idea is that providing copypast answers is unfair. Yes, it's unfair - life itself is unfair. Students who get used to such copypaste graduate with low qualification and will be disqualified during job interviews - that is also "unfair", but that's what they asked for.
sharptooth
@sharptooth: sorry but it’s a loong shot between “life’s unfair” and “I act unfairly / support such behaviour”.
Konrad Rudolph
@Konrad Rudolph: You give such weight to it as if I helped that guy commit suicide.
sharptooth
+2  A: 

This algorithm is quite easy. Try decomposing the problem:

  • How would you add all numbers <= some n recursively?
    • Have an appropriate base case (hint: either x = n or x = 0 depending on how you start),
    • Add the current number to the return value,
    • Call the function again (recursion, duh), add its result to the return value.
  • Now, just add a test in every recursive step to see whether the number is even.
Konrad Rudolph
A: 

Algorithms only:

def sumeven (n):
    if n <= 0:
         return 0
    if n is even:
         return n + sumeven (n-1)
    return sumeven (n-1)

As with all recursive problems, break it down into:

  • the terminating (lowest-level) value.
  • all other values defined in terms of a "lower-level" value.

In the above case, the rules are:

f(0) is 0.
f(n) is f(n-1) for all odd values of n.
f(n) is n + f(n-1) for all even values of n.

This can be optimised to skip odd values (other than the first), if necessary, by changing that last rule to:

f(n) is n + f(n-2) for all even values of n.

giving the algorithm:

def sumeven (n):
    if n <= 0:
         return 0
    if n is odd:
        return sumeven (n-1)
    return n + sumeven (n-2)
paxdiablo
+1  A: 

It is relatively simple to write in c with a for loop

sum = 0;
for (int i=0; i<=n; i+=2)
   sum += i;

if you want a recursive function you could do something like this (again, in c)

int sum(int n){
   if (n==0) return 0;
   if (n%2) return sum(n-1);
   return n+sum(n-2);
}

This sounds very homework-ey, I do hope you are going to learn from this and other answers and not just copy and paste.

EDIT Thanks for that oezi, fully missed it.

suicideducky
i<n should be i<=n, but then it's perfect.
oezi
+3  A: 




Initially, the solution is :

int SumEven(int n)
{
   return (n/2)*(1+(n/2));
}






And to make it recursive:

int SumEven(int n,unsigned int y)  // y has completely no effect!!
{
   if(y==0)
       return (n/2)*(1+(n/2));
   else 
      return SumEvent(n,y-1)
}






                                            (^_^)







Betamoo
Made me do a double take and read through the second time very carefully, love the changing smileys, bonus points if he submits this as the answer to his homework xD
suicideducky
I tried to use recursion in solving this problem... And that solution was the best I could think of....
Betamoo
+1  A: 
(defun sum-twos (n)
  "This will sum the even numbers between 0 and N (inclusive)"
  (if (= 1 (mod n 2))
      (sum-twos (- n 1))
      (if (> n 0)
          (+ n (sum-twos (- n 2)))
          (+ n 0))))
LanceH
Tip: use `cond` instead of nested `if`s.
Svante