# Range, Reverse, Sum!

Given a positive integer n as input, output the reversed range sum of n.

A reversed range sum is created by making an inclusive range up to n, starting with 1 and including n, reversing each of the numbers inside, and summing it.

Example:

Here is what would happen for an input of 10:

Range: [1,2,3,4,5,6,7,8,9,10]

Reverse: [1,2,3,4,5,6,7,8,9,01] (1-char numbers reversed are themselves, 10 reversed is 01 or 1)

Sum: 46

Numbers with 3+ digits are reversed the same way numbers with 2 digits are. For example, 1234 would become 4321.

Test cases:

Input -> Output

10 -> 46
5 -> 15
21 -> 519
58 -> 2350
75 -> 3147
999 -> 454545


Complete text cases to input of 999 can be found here, thanks very much to @fireflame241.

• More test case results (not numbered, sorry, but you can parse through and get their line number if you want): Try it online! Jul 31, 2017 at 23:49
• @StepHen >:D Charcoal is faster Aug 1, 2017 at 0:36
• Relevant Aug 1, 2017 at 1:12
• OEIS A062918 Aug 1, 2017 at 6:37
• -1 because this is uninteresting. It seems like most, if not all, of the submissions are using the same approach. This challenge seems like a bunch of problems that have already been asked, just piped together with no obvious shortcuts. Aug 21, 2017 at 8:23

# 05AB1E, 3 bytes

### Code

LíO


Uses the 05AB1E encoding. Try it online!

### Explanation

L       # Range
í      # Reverse
O     # Sum

• dat explanation tho Aug 1, 2017 at 0:41
• @ETHproductions well Reverse should be Reverse each actually... Aug 1, 2017 at 8:31
• @EriktheOutgolfer It's not vectorized? Aug 1, 2017 at 10:40
• @ASCII-only 05AB1E vectorization is really 1 level deep, not ∞. Also just "reverse" is R, while í is "reverse each". Aug 1, 2017 at 10:43

# Bash + GNU utils, 24

seq $1|rev|paste -sd+|bc  ### Explanation seq$1                    # range
|rev                # reverse (each line)
|paste -sd+|bc  # sum


## JavaScript (ES6), 42 bytes

f=n=>n&&+[...n+""].reverse().join+f(n-1)


My favorite doubly-recursive solution is unfortunately 3 bytes longer:

f=n=>n&&+(g=x=>x?x%10+g(x/10|0):"")(n)+f(n-1)


# Perl 6, 20 bytes

{(1..$_)».flip.sum}  Test it ## Expanded: { ( 1 ..$_ )\  # Range
».flip        # flip each value in the Range (possibly in parallel)
.sum          # sum up the list
}

• Is the 'possibly in parallel' required? Seems like you could get rid of a byte or two by omitting it.
– Nic
Aug 2, 2017 at 16:17
• @QPaysTaxes No. The ».flip calls the .flip method on each of the values in the Range. The next shortest way to do this is .map(*.flip) which is 5 bytes more. Aug 5, 2017 at 15:49
• Oh, so the key part is "each", not "(possibly in parallel)". Might be worth splitting them out, then.
– Nic
Aug 5, 2017 at 22:28
• @QPaysTaxes I'm not sure I know what you mean ».flip is a hyper method call. While I can split up the » and .flip by using an unspace \  like I did before it; that would make it harder to understand, as it would look like the end of a qqww/ / construct (« a b "c d" »). Aug 6, 2017 at 14:59

# C (gcc), 63 bytes

f(n){int t=0,c=n;for(;c;c/=10)t=t*10+c%10;return n?t+f(n-1):0;}


Try it online!

# Retina, 4136 35 bytes

.+
$* 1 1$¶
1+
$.& %O^$.

.+
$* 1  Try it online! Link includes test cases. Edit: Saved 5 bytes thanks to @FryAmTheEggman. Saved 1 byte thanks to @PunPun1000. Explanation: .+$*


Convert to unary.

1
1$¶  Create a range from 1 to n. 1+$.&


Convert back to decimal.

%O^$.  Reverse each number. .+$*


Convert back to unary.

1


Sum and convert back to decimal.

• @FryAmTheEggman Bah, I keep forgetting about that.
– Neil
Aug 1, 2017 at 7:54
• You don't need the ¶ in the .+¶ The match will match across lines Aug 1, 2017 at 16:35
• @PunPun1000 I did need it before FryAmTheEggman's fix!
– Neil
Aug 1, 2017 at 17:31
• I notice that O^$s. to reverse the whole string also works. – Neil Nov 25, 2017 at 17:20 # Python 2, 38 bytes Can't compute higher terms than the recursion limit: f=lambda x:x and int(x[::-1])+f(x-1)  Try it online! • You can use import sys and sys.setrecursionlimit() if you want to handle larger numbers, in the tio header. Aug 1, 2017 at 6:01 # Jelly, 4 bytes Ṛ€ḌS  Try it online! ### How? Ṛ€ḌS - Link: n Ṛ€ - reverse for €ach (in implicit range) Ḍ - convert from decimal list (vectorises) S - sum  • I KNEW there had to be a way to use Range implicitly, +1 Aug 1, 2017 at 11:19 # Haskell, 34 bytes \n->sum$read.reverse.show<$>[1..n]  Simple and straightforward. # cQuents, 4 bytes ;\r$


Try it online!

## Explanation

       Implicit input n.
;      Series mode. Outputs the sum of the sequence from 1 to n.
\r$Each item in the sequence equals: \r String reverse of$                     current index (1-based)


# Brachylog, 4 bytes

⟦↔ᵐ+


Try it online!

### Explanation

⟦↔ᵐ+
⟦        range from 0 to input
↔ᵐ      map reverse
+     sum


# Python 2, 50 47 bytes

-3 bytes thanks to officialaimm!

lambda n:sum(int(i+1[::-1])for i in range(n))


Try it online!

• since it's python 2,  instead of str saves 3 bytes. Aug 1, 2017 at 4:53

# Röda, 5641 36 bytes

15 bytes saved thanks to @fergusq

{seq 1,_|parseInteger$_[::-1]|sum}  Try it online! This is an anonymous function that takes an integer from the input stream and outputs an integer to the output stream. ### Explanation {seq 1,_|parseInteger$_[::-1]|sum} Anonymous function
seq 1,_                             Create a sequence 1 2 3 .. input and push each value to the stream
|                            For each value in the stream:
$_ Cast it into a string [::-1] And reverse it parseInteger And parse the resulting string as an integer, while pushing the value to the stream |sum Sum all the values in the stream  • You can save a lot of bytes by using [::-1] instead of reverse. Also  $_  is shorter than _.."" and parentheses after parseInteger are not needed. Aug 2, 2017 at 7:31
• @fergusq Thanks for the tips, my Röda has gone a bit rusty :) Aug 2, 2017 at 9:16

# C# (.NET Core), 103 97 bytes

using System.Linq;r=>new int[r+1].Select((_,n)=>int.Parse(string.Concat((n+"").Reverse()))).Sum()


Try it online!

TIO link outputs all the results from 1 to 999, so feel free to check my work.

I expected this to be a bit shorter, but it turns out Reverse() returns an IEnumerable<char> instead of another string so I had to add some extra to turn it back into a string so I could parse it to an int. Maybe there's a shorter way to go from IEnumerable<char> to int correctly.

Of minor note, this also uses the functions Range() Reverse() and Sum() all in order.

-6 bytes thanks to TheLethalCoder

• You don't need the trailing semi colon. I think using new int[r] and .Select((_,n)=>...) will save you bytes. Aug 1, 2017 at 8:15
• @TheLethalCoder It takes new int[r+1] to get the right output since the index starts at 0, but it does still save a few bytes. RIP Range() though Aug 1, 2017 at 12:19

# APL (Dyalog), 10 7 bytes

3 bytes golfed thanks to @Adám by converting to a tradfn from a train

+/⍎⌽⍕⍳⎕


Try it online!

⎕          Input (example input: 10)
⍳          Range; 1 2 3 4 5 6 7 8 9 10
⍕          Stringify; '1 2 3 4 5 6 7 8 9 10'
⌽          Reverse; '01 9 8 7 6 5 4 3 2 1'
⍎          Evaluate; 1 9 8 7 6 5 4 3 2 1
+/         Sum; 46

• To @Uriel & Cows quack about the chat question: Well, I did the Mathematics portion, in addition to that, I've been suspended from chat, hence my not responding in there. Aug 1, 2017 at 14:57
• 7 bytes: +/⍎⌽⍕⍳⎕
Aug 2, 2017 at 9:27
• @Adám Thanks for the tip. Removing the ¨ was clever :) Aug 2, 2017 at 9:40

# Ruby, 56, 52, 41, 39 bytes

->n{(1..n).sum{|i|i.to_s.reverse.to_i}}


# Ruby, 34 bytes (if lambda param is a string)

->n{(1..n).sum{|i|i.reverse.to_i}}


Thanks to @Unihedron for the second solution.

• ->n{ works as well. Aug 15, 2017 at 18:27
• I have crafted a shorter program in the same tool (Ruby) that is different enough (it deals with input and output) to be its own submission, you can find it here: codegolf.stackexchange.com/a/150636/21830 Dec 14, 2017 at 17:50
• @Unihedron, haha, I didn't know Ruby is so crazy to allow string ranges. Thanks. Dec 14, 2017 at 18:53
• Yes, ruby also has nifty features like ?a..?z and ?a1..?h8 (although you better be careful with the 2nd format :D) Dec 14, 2017 at 19:19
• Ranges has to either 1. (for start value) implement succ and 2. (if either start or end value does not implement succ) be numeric, so int..string will get rejected as "Bad value for range". The inverse is true (but alas there's no downto range), or (?1..n) can be used instead Dec 14, 2017 at 19:39

# Mathematica, 47 bytes

Tr[FromDigits@*Reverse/@IntegerDigits@Range@#]&


Try it online! (in order to work on mathics we need to replace "Tr" with "Total")

• Tr@*IntegerReverse@*Range Aug 21, 2017 at 22:20

# Charcoal, 14 13 bytes

-1 byte thanks to Carlos Alejo

Ｉ∕…·⁰Ｎ«⁺ιＩ⮌Ｉκ


Try it online! Link is to verbose version.

## Explanation

Ｉ                  Cast
∕     «           Reduce
…·⁰Ｎ            Inclusive range from 0 to input as number
⁺          Plus
ι         i
Ｉ⮌Ｉκ   Cast(Reverse(Cast(k)))

• You can save a byte by dropping the last ». By the way, where in the Charcoal wiki is the Reduce operator documented? Aug 1, 2017 at 6:04
• Nowhere, it's an overload of the division one :| I can give you edit access if you want (sorry I'm too lazy to do it myself) Aug 1, 2017 at 7:07
• Also yeah I forgot why leaving out ending braces works lol Aug 1, 2017 at 7:08
• I would really like the Charcoal wiki to be a bit more documented, as there are still some working but hidden features. If you grant me edit access I'll do my best to document them. Example: how can the Modulo operator be used to format strings in Charcoal? Aug 1, 2017 at 7:38
• @CarlosAlejo I've had a bit of free time so I've started documenting stuff, hope you like it!
– Neil
Aug 3, 2017 at 13:31

## Magneson, 102 bytes

That's not very visible, so here's a scaled up version (Note: Won't actually run, and still isn't very pretty)

Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:

• R: 0, G: 1, B: 1 is an integer assignment command, which takes a string for the variable name and the value to assign. We'll use this to store the sum total.
• R: 0, G: 1, B: 0 is a prebuilt string with the value VAR_1 (Note: This is only while we're asking for a string; the colour code has a separate function when used elsewhere).
• R: 3, G: 0, B: 0 is a raw number. Magneson handles standard numbers by requiring the Red component to be exactly 3, and then forms a number by using the blue value directly plus the green value multiplied by 256. In this case, we're just getting the number 0.
• R: 0, G: 1, B: 1 is another integer assignment command. This time, we're storing an iteration variable, to keep track of which number we're on
• R: 0, G: 1, B: 1 is a prebuilt string with the value VAR_2 (Once more, only when we need a string)
• R: 3, G: 0, B: 0 is the number 0, once more. Onto the interesting bits now.
• R: 1, G: 0, B: 0 indicates the start of a loop. This takes a number and loops the following snippet of code that many times.
• R: 2, G: 0, B: 0 is the STDIN function, or at least it is when we need a number. This reads a line of input from the console and turns it into a number, since we asked for a number.
• R: 0, G: 8, B: 0 starts off our looping code, and it is an additive command. This adds a number to an integer variable, and so takes a string for the variable name, and the number to add.
• R: 0, G: 1, B: 1 is the prebuilt string for VAR_2, which is our iteration variable.
• R: 3, G: 0, B: 1 is a raw number, but this time it's the number 1.
• R: 0, G: 8, B: 0 is another addition command.
• R: 0, G: 1, B: 0 is the string for VAR_1, which is our sum total.
• R: 0, G: 3, B: 0 is a function that reverses a string. In the context of asking for a number, it then converts the reversed string to a number.
• R: 0, G: 2, B: 1 is an integer retrieval command, and will retrieve the number stored in a provided variable. In the context of asking for a string (such as from the reverse command), it converts the number to a string.
• R: 0, G: 1, B: 1 is the name VAR_2; our iteration variable.
• R: 1, G: 0, B: 1 is the marker to end the loop, and go back to the start of the loop if the criteria isn't met (so if we need to keep looping). Otherwise, proceed onwards.
• R: 0, G: 0, B: 1 is a very simple println command, and takes a string.
• R: 0, G: 2, B: 1 retrieves an integer from a variable
• R: 0, G: 1, B: 0 is the name of our sum total variable, VAR_1

All in all, the program:

• Assigns the value 0 to VAR_1 and VAR_2
• Loops from 0 to a number provided in STDIN
• Adds one to VAR_2
• Adds the integer value of reversing VAR_2 to VAR_1
• Prints the contents of VAR_1

# CJam, 12 bytes

ri){sW%i}%:+


Try it online!

Explanation:

ri){sW%i}%:+
r            Get token
i           To integer
)          Increment
{sW%i}    Push {sW%i}
s         To string
W        Push -1
%       Step
i      To integer
%   Map

• Could you add an explanation? I don't understand CJam (nor GolfScript). But MY beat two (albeit ancient in terms of golf-langs) golfing languages! Aug 1, 2017 at 15:18
• @Zacharý done... Aug 1, 2017 at 15:23
• You don't need the , Aug 1, 2017 at 17:36
• @BusinessCat Ohhh used too much to GolfScript apparently... Aug 1, 2017 at 17:36

# Java 8, 97 bytes

IntStream.range(1,n+1).map(i->Integer.valueOf(new StringBuffer(""+i).reverse().toString())).sum()


EDIT

As per the comment of Kevin Cruijssen, I would like to improve my answer.

# Java 8, 103 bytes

n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum()

• Integer.valueOf can be golfed to new Integer, and .reverse().toString() can be golfed to .reverse()+"". Also, you must include the required imports and lambda parameters, like java.util.stream.IntStream and n-> before it. And you can also golf IntStream & Integer to LongStream and Long. The final answer will be n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum() (103 bytes - Your current answer with added import and lambda parameter would be 117 bytes.) Still +1, nice answer! Aug 3, 2017 at 13:01
• @KevinCruijssen Thank you for your valuable inputs. I'll update my answer. Thanks. :) Aug 3, 2017 at 13:22

# Japt, 7 5 bytes

-2 bytes thanks to @Shaggy.

õs xw


Try it online!

## Explanation

õs xw  Implicit input of integer U
õs     Create range [1,U] and map to strings
w  Reverse each string
x   Sum the array, implicitly converting to numbers.


# Old solution, 7 bytes

Keeping this since it's a really cool use of z2.

õs z2 x


Try it online!

## Explanation

õs z2 x  Implicit input of integer U
õs       Create range [1,U] and map to strings
z2    Rotate the array 180°, reversing strings
x  Sum the array, implicitly converting back to integers

• You know z2 on a flat array is the same as w, righ... uhm... excuse my inadequacy at Japt... Aug 1, 2017 at 0:43
• 6 bytes: õ_swÃx thanks to the new addition of N.s(f). Aug 15, 2017 at 16:00
• Or even just õs xw for 5 bytes. Aug 15, 2017 at 16:04
• @Shaggy I can't believe nobody mentioned that 5-byte solution until now... will edit in a bit. As for the 6-byte one, if that was added after this challenge was posted, I think that'd be non-competing. Aug 15, 2017 at 16:15
• @JustinMariner, neither can I! :D Although, it seems a shame to ditch that z2 trick; that was pretty damn genius. Note that non-competing is no longer a thing. Aug 15, 2017 at 16:29

## C++, 146 bytes

#include<string>
using namespace std;int r(int i){int v=0,j=0;for(;j<=i;++j){auto t=to_string(j);reverse(t.begin(),t.end());v+=stoi(t);}return v;}

• Good job! You can spare some bytes by removing the header and putting "using namespace std" (check here tio.run/#cpp-gcc). I also think you could replace "auto t" with just "t" (?) Aug 1, 2017 at 6:33
• Yeah, koita_pisw_sou is right about the first part. But you need the auto. Aug 1, 2017 at 12:24
• @koita_pisw_sou Do you mean that i can exclude the header directive from the byte count ? Same for the namespace ? auto keyword is needed Aug 1, 2017 at 13:43
• Yes, check the link I sent Aug 1, 2017 at 13:44
• (Whoops, I am not sure about the removing the header!) But I was referring to using namespace std; saving bytes. Aug 1, 2017 at 15:00

# Husk, 7 6 3 bytes

ṁ↔ḣ


Try it online!

### Ungolfed/Explanation

  ḣ  -- With the list [1..N] ..
ṁ    -- .. do the following with each element and sum the values:
↔   --    reverse it


# Perl 5, 29 27 22 + 1 (-p) = 23 bytes

map$\+=reverse,1..$_}{


Try it online!

• 26 bytes: map$r+=reverse,1..<>;say$r. Dec 29, 2017 at 9:35
• Got it down even further using -p Dec 30, 2017 at 6:44

# Gol><>, 26 bytes

&IFLPWaSD$|~rlMFa*+|&+&|&h  Try it online! ## Explanation &I &h < register init, read "n"; print register (h = n;) FLP | < For loop, do "n" times for each x in [1] to [n] WaSD$|                < modpow "x" to digits: [123] [3 12] [3 2 1] [3 2 1 0]
~rlMFa*+|       < Ditch zero, reverse stack, build the number back
&+&    < register += final x


# Vyxal, s, 2 bytes

ƛṘ


Try it Online!

• Here's a test suite if you're interested. Feb 28, 2021 at 7:20
• As impressive as this is, I think flags should be included in the bytecount, as the program would not have worked this way if it wasn't for the flag
– Dion
Feb 28, 2021 at 7:37
• @Dion it was decided that flags don't have to be byte count over on meta. If I didn't have that policy backing me up, vyxal wouldn't have flags at all. Feb 28, 2021 at 10:01
• new codepage version Apr 10, 2021 at 0:22
• Idea: allow usage of older versions on the webpage and add that as a link parameter Apr 10, 2021 at 2:47

# vim, 49 46 bytes

A@q<ESC>0"bDa1<ESC>qqYp<C-a>q@bdk:%s/$/+ :%!rev xVGJ:%!bc  <ESC> is 0x1b, <C-a> is 0x01, <NL> is 0x0a. ## Annotated A@q<ESC>0"bD # put {N}@q (run macro q N times) in register b a1<ESC> # buffer now contains "1" qqYp<C-a>q # store macro that copies and increments the last line in register q @bd1k # run {N} times, then delete the extra lines # (can't just run {N-1} times, or it won't handle N=1 correctly) :%s/$/+<NL>   # append + to each line
:%!rev<NL>    # reverse each line
VGJ           # join lines
:%!bc<NL>     # sum


Try it online!

# Vim, 3937 28 bytes

D@"O<C-V><C-A>0<ESC>V{g<C-A>:%!rev
v}gJS0<ESC>@"


Try it online!

Tons of bytes saved thanks to some great advice by user41805

### Explanation

Step 1: build the range (with summing commands included)
D@"O<C-V><C-A>0<ESC>V{g<C-A>
D                               Delete the input number
@"            <ESC>            Do that many times:
O                              Insert a new line above
<C-V><C-A>                    Write a <C-A> byte (\x01)
0                   Followed by a 0
V{          Select all the lines just written
g<C-A>    Turn the numbers into an increasing range

Step 2: reverse each number

:%!rev (that's it)

This will produce a sequence of lines with the reversed number followed by <C-A>, which is the command to increase a value by the reversed number. Leading 0s actually move the pointer to the beginning of the line, so they are effectively ignored.

Step 3: sum them all up
v}gJS0<ESC>@"
v}               Select all the lines to the end of the file
gJ             Join them
S            Replace this line
0<ESC>         with a 0
@"    Execute the replaced line as commands


# RProgN 2, 8 bytes

{Ø.in}S+


## Explained

{Ø.in}S+
{    }S # Create a stack in range 0 through the implicit input, using the function defined
Ø.     # Append nothing, stringifying the number
i    # Reverse the string
n   # Convert back to a number
+# Get the sum of the stack, and output implicitly.
`

Try it online!