DEV Community

Calvin
Calvin

Posted on • Edited on

Repl Coding Challenge:Basic Recursion 👯

The problem gives a positive integer number. The challenge requires one to fill in the method sum so that it adds up all positive integers that make up the number and returns the sum.

The recursive solution is written in Ruby. Thank you for your comments and reviews.

Recursive Solution:



```

def sum(number) return 1 if number == 1 number + sum(number - 1) end

``` ruby

Video Walkthrough

Top comments (4)

Collapse
 
gypsydave5 profile image
David Wickes

Hey - looks like you're writing Ruby 😁. Try taking up the post to mention the language, and add the name of the language to the fenced code block at we get done syntax highlighting.

Nice use of inject there - build the list of numbers then sum them. Can you solve this without using an array? Can you solve it with a recursive method?

Collapse
 
calvinoea profile image
Calvin

Hey, David. Thanks a lot for your review and feedback 😁. I have added a recursive solution as well as the name of the language. What do you think of it now?

Collapse
 
gypsydave5 profile image
David Wickes

Nice work on the recursive solution.

Now let's make your code look pretty!

On the opening of your block of code

```

Put the language in





 ```ruby

And it'll look like this

def sum(number)
  return 1 if number == 1
  number + sum(number - 1)
end
Thread Thread
 
calvinoea profile image
Calvin

Thank you, David!