DEV Community

Calvin
Calvin

Posted on • Edited on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay