title: Round towards zero

text:
# Question
Title: Round towards zero
This is a simple task. Given a positive or negative real number, round it to the next whole integer closer to zero.

# The challenge

* Take input through any reasonable form (stdin, function, etc.) of one positive or negative real number.
* Round this number "towards zero" - this means if it is positive you will round down, and if it is negative you will round up.
* Return the number or output it to the console.

# Test cases

```
 1.1   =>  1
 1.9   =>  1
-1.1   => -1
 500.4 =>  500
-283.5 => -283
 50    =>  50
-50    => -50

```

# Rules

Have fun! more Jimmy challenges coming soon

# Answer
# Jelly, 1 byte

```
r

```

A full program (as a monadic Link it returns a list of length one).

**Try it online!**

### How?

```
r - Main Link: number, X           e.g. -7.999
r - inclusive range between left (X) and right (X) (implicit cast to integer of inputs)
  -  = [int(X):int(X)] = [int(X)]       [-7]
  - implicit (smashing) print            -7

```
> 14 votes

# Answer
# Python 3, 3 bytes

```
int

```

Try it online!

Truncates the digits after the decimal point.

*NOTE: This is a trivial answer. Please take a look at the other answers before upvoting*
> 43 votes

# Answer
# Python 2, 3 bytes

```
int

```

Try it online!
> 23 votes

# Answer
# Perl 5 `-p056l15`, 2 bytes

```
<>

```

Try it online!

### How does that work?

```
-056   # (CLI) Make "." the input record separator
-l15   # (CLI) Make "\n" the output record separator
       # (otherwise it would use the input separator)
-p     # (CLI) Implicitly read $_ from STDIN
<>     # Read the second input field and do nothing with it
-p     # (CLI) Output $_ to STDOUT

```

Or if you prefer a more traditional answer:

### Perl 5, 6 bytes

```
$_=int

```

Try it online!
> 14 votes

# Answer
# Labyrinth & Hexagony, 3 bytes

Thanks to FryAmTheEggman for pointing out I'd written some Hexagony!

```
?!@

```

**Try it online!** & **Try it online!**

### How?

Labyrinth and Hexagony will both tell you as early as possible!...

```
? - read and discard from STDIN until a digit, a - or a + is found. Then read as many characters as possible to form a valid (signed) decimal integer and push its value
! - pop a value and write its decimal representation to STDOUT
@ - exit the labyrinth

```
> 9 votes

# Answer
# brainfuck, 26 bytes

```
,[.+++++[->+++++<]>+[,>]<]

```

Try it online!

Outputs with a trailing `.` if the number was a decimal

There's not much specual golfing wise, except that instead of subtracting 46 to check if a character is a `.`, I add 5 and multiply by 5 to get 255, then add one more to roll over to zero. Subtracting 3, multiplying by 6 and subtracting 2 is the same bytecount
> 6 votes

# Answer
## C (tcc), ~~39~~ ~~21~~ 10 bytes

I was actually quite surprised nobody thought of using C.

```
f(float i){}

```

This is not an identity function as it seems to be. The implicit int type of the f function trunctuates the floating-point.

TIO

Less likely to trick people but has a shorter byte length:

```
f(int i){}

```

TIO
> 6 votes

# Answer
# Perl 6, 4 bytes

```
*+|0

```

Anonymous function.

Try it online!
> 4 votes

# Answer
# Ruby, 11 bytes

```
proc &:to_i

```

I picked this one because it distinguishes itself from the lambdas that us Ruby golfers typically use (thankfully, it had the same bytecount as the "traditional" solution):

```
->n{n.to_i}

```

Try it online!
> 4 votes

# Answer
# , 6 bytes

```
**<.@|

```

Try it online!

Sign `*` times `*` the round down `<.` of the absolute value `@|`
> 4 votes

# Answer
# , ~~13~~ 5 bytes

Thanks Robin Ryder

```
trunc

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 5 bytes

```
\..*

```

Try it online! Link includes test cases.
> 3 votes

# Answer
# JavaScript, 6 bytes

```
x=>x^0

```

Try it online!

---

# JavaScript, 8 bytes

Using built in is 2 bytes longer...

```
parseInt

```

Try it online!
> 3 votes

# Answer
# Java (OpenJDK 8), 15 bytes 9 bytes

```
s->(int)s

```

Try it online!

thanks to @kevin-cruijssen
> 3 votes

# Answer
# Whitespace (with vii5ard compiler), ~~18~~ 17 bytes

```
[S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online. You'll have to copy-paste the code yourself (note that SE converts the tabs to a bunch of spaces!) in order to run the code at the online Whitespace-compiler vii5ard. When clicking run, it will ask for an input (i.e. `-283.5`), and after clicking enter it will continue and output `-283`.

**Explanation in pseudo-code:**

```
Integer i = STDIN as integer
Print i as integer

```

Whitespace can only use I/O as integers or single characters, so in this case, the input is read as integer and all other subsequent characters are ignored. I.e. `-283.5` or `-283abc5` would both be input (and thus output) as `-283`.

Unfortunately this above doesn't work on TIO for two reasons (all Whitespace compilers are slightly different..):

1. It will give a `no parse` error when we try to read an input as integer, which isn't an a valid integer. So, instead we'll read one character at a time, and stop (with an error) as soon as we've encountered the `.` or there is no more input (i.e. `50`/`-50`).
2. In the vii5ard compiler it's also possible to push 0 with just `SSN`, whereas on TIO it requires an additional `S` or `T`: `SSSN`/`SSTN`. The first `S` is *Enable Stack Manipulation*; the second `S` is *Push what follows as integer*; the third `S`/`T` is positive/negative respectively; and any `S`/`T` after that (followed by an `N`) is the number we want to push in binary, where `S=0` and `T=1`. For integer 0 this binary part doesn't matter, since it's 0 by default. But on TIO we'd still have to specify the positive/negative, and with most other Whitespace compilers like vii5ard not.

# Whitespace (with TIO compiler), 48 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S S S T S T T   T   S N
_Push_46_.][T   S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start LOOP:
  Character c = STDIN as character
  If(c == '.'):
    Exit program
  Print c as character
  Go to the next iteration of LOOP

```
> 3 votes

# Answer
# K (oK), 3 bytes

```
`i$

```

Try it online!
> 3 votes

# Answer
# Excel, 10 bytes

```
=TRUNC(A1)

```

`TRUNC` truncates a number to an integer by removing the fractional part of the number.
> 3 votes

# Answer
# Husk, 3 bytes

```
→…0

```

Try it online!

Takes a range  from 0 toward the input, then gets its last element . For a positive input this goes like `3.3; [0,1,2,3]; 3`. For a negative input this goes like `-3.3; [0,-1,-2,-3]; -3`.
> 3 votes

# Answer
# ReRegex, 12 bytes

```
\..+//#input

```

Try it online!

ReRegex is a programming language which matches and replaces over and over until there are no matches.

```
MATCH
    \.                                      The literal period/full stop char
    .+                                      Followed by one or more characters
REPLACE
    (nothing)                               Equivalent to removing the input
STRING TO REPEATEDLY MATCH/REPLACE UNTIL THERE ARE NO MATCHES
    #input                                  The input

```
> 2 votes

# Answer
# V (vim), 4 bytes

```
Á.#D

```

Try it online!

Thanks @DJMcMayhem, 1 byte saved.
> 2 votes

# Answer
# Intel 8087 FPU machine code, 9 bytes

```
00000000: d92e 0701 d9fc c37f 0f                 .........

```

Listing:

```
D9 2E 0107      FLDCW   CW_RNDDN    ; set FPU CW for truncate (floor) rounding mode
D9 FC           FRNDINT             ; ST = ROUND_TO_ZERO( ST )
C3              RET                 ; return to caller
    CW_RNDDN    DW  0F7FH           ; control word to round down

```

Callable function, input is in `ST(0)`, output to `ST(0)`.

The 8087 must first be put into round towards zero mode by setting the control word (`0F7FH`). Rounding towards zero would then take place.
> 2 votes

# Answer
## Keg, ~~19~~ ~~17~~ 13 bytes

This outputs some trailing unprintable characters. Also, this exits with an error. (Now we need reversed input!)

```
?'(:\.>')"([,

```
> 2 votes

# Answer
# Aheui (esotope), 9 bytes

```
방망희

```

Try it online!

Basic idea from that of triangular answer (or any other languages takes numeric input as integer).

Fun fact. `방망희`(pronounced `bang-mang-heui`(`a` of `ark`)) sounds almost same as `방망이`(pronounced `bang-mang-i`(`a` of `ark`, `i` sounds like `E`), which means bat.

### How does it works?

takes number as integer.

prints value as number.

terminates program.
> 2 votes

# Answer
# Red, 4 bytes

```
to 1

```

Try it online!

Just converts the float to an integer (conversion by prototype)
> 2 votes

# Answer
# Zsh, 10 bytes

```
<<<$[0^$1]

```

`xor` with 0. I came across this during another challenge recently. Try it online!

Does not work in Bash or POSIX sh (dash).
> 2 votes

# Answer
## GNU sed, 8 bytes

```
s:\..*::

```

Try it online!

GNU sed has no concept of numbers. The code removes all text after and including the dot.
> 2 votes

# Answer
# \>\<\>, 6 bytes

```
:1%-n;

```

Try it online!

Assuming the input is pushed onto the stack. The language specification allowed doing so:

> While parsing numbers is not very hard, it makes for slow and possibly glitchy programs. Most programs requiring number input reads it from the stack at program start. This is done with an interpreter that supports pre-populating the stack with values.

**Explanation:**

```
:      Duplicated the input
 1%    Take the fractional part
   -   The original input minus the fractional part, results in the integer part
    n  Output as a number
     ; Terminates

```

If error is allowed:

# \>\<\>, 5 bytes

```
:1%-n

```

Try it online!

The `n` command at the end **pops** and outputs the top of the stack. Then, the IP returns to the first character(because the code is laid out in a torus), and reached a "duplicate" command when the stack is empty. Thus, it errors and terminates.
> 2 votes

# Answer
# Husk, 4 bytes

```
←x'.

```

Try it online! Splits the string on `'.'` and takes the first segment.
> 2 votes

# Answer
# Pip, 5 bytes

```
a//:1

```

Try it online!
> 1 votes

# Answer
# Triangular, 3 bytes

```
$.%

```

Try it online!

Triangular takes numeric input as an integer; any decimal values are truncated. If it's acceptable to just leave the input on the stack without printing it, then this solution can instead be:

---

# Triangular, 1 byte

```
$

```

Try it online!
> 1 votes

# Answer
# Haskell, 8 bytes

```
truncate

```

Try it online!

A built-in that truncates the non-integer part of the number.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 9 bytes

```
n=>(int)n

```

Try it online!
> 1 votes

# Answer
# Japt `-P`, 1 byte

```
ì

```

Try it

Alternative 2-byte solution that doesn't use flags:

```
|0

```

Try it

The `|` operator to coerces the input value to an integer.

There may be a 1-byte solution without flags, but I have not come up with it yet.
> 1 votes

# Answer
# 05AB1E, 1 byte

```
ï

```

In the legacy version (which is written in Python), the cast to integer builtin works as expected to truncate the decimal values.

Try it online.

In the new version of 05AB1E (written in Elixir) it only works on strings (even though integers/decimals/strings should all be interchangeable, unless sorting lexicographical vs numeric for example). Guess I can report a bug to *@Adnan*..

Try it online to compare integer/decimal input (giving incorrect result) vs string inputs (giving correct results).
> 1 votes

# Answer
# Scala, 7 bytes

```
_.toInt

```

Try it online!
> 1 votes

# Answer
# `ed(1)`, 40 bytes

try it out on the intertubes

```
g/-0.*/s//0/
,s/\([0-9\-]*\).*/\1/gp
w
.

```

Someone on twitter was rather impolite about using **`ed`**:
> 1 votes

# Answer
# PowerShell, 19 bytes

```
$args-replace'\..*'

```

Try it online!

PowerShell by default does bankers' rounding, which is pretty much the opposite of how many other languages do rounding. So, traditionally we'd use `[Math]::Truncate()` to strip the decimal point and any decimal part and achieve the "to zero" rounding we're interested in here. However, that's a bit long, so using this tip, we can round-toward-zero by implicitly casting the input to a string, performing a regex `-replace` to get rid of the period and anything after it, and leaving the output on the pipeline for implicit printing.
> 1 votes

# Answer
# Brachylog, 6 bytes

```
↔a₁↔ịℤ

```

Try it online!

Takes input as a string.

```
↔a₁↔      The longest prefix of the input
    ị     which converted to a number
     ℤ    is an integer, is the output (as an integer).

```
> 1 votes

# Answer
# 33, 2 bytes

```
Oo

```

Try it online!

Simple solution. 33 doesn't support floating-point numbers, so getting input will only retreive the integer part of it, truncating the decimal places.
> 1 votes

# Answer
# Stax, 5 bytes

```
i'./h

```

Run and debug it

Splits as a string on `"."` and returns the first part.
> 1 votes

# Answer
# PHP, 6 bytes

Built-in function:

```
intval

```

Try it online!

---

# PHP, 11 bytes

Full program:

```
<?=0^$argn;

```

Try it online!
> 1 votes

# Answer
## Julia (1.2), 5 bytes

```
trunc

```

### Full program, 24 bytes

```
print(trunc(readline()))

```
> 1 votes

# Answer
# APL, 5 bytes

```
××⌊∘|

```

Explanation: This is a fork; when evaluated at a number *r*, it computes:

```
(×r) × (⌊∘|r)

```

i.e. sign(r) x floor(abs(r))
> 1 votes

# Answer
# MAWP, 41 bytes

```
%|0~59WA{59WM}<59WM;>[85W6MA?.{85W6MM;}]

```

-3 bytes after rearranging the beginning conditionals.

-1 byte from Dion after replacing `<>` with `?`

Checks for `-` in the first character, then prints number using ASCII values till a `.` is reached.

Try it!
> 1 votes

# Answer
# Keg, 7 bytes

```
{:\.≠|,

```

Try it online!

It's **J**ust **A** **P**ort of the MAWP program because maths is overrated. ;p
> 1 votes

# Answer
# Whispers v3, ~~32~~ 30 bytes

```
> Input
>> ⌈1⌋
>> Output 2

```

Try it online!

-2 bytes from Michael Chatiskatzi.
> 1 votes

# Answer
# Vyxal, 1 byte

```
I

```

Try it Online!

Casts input to int, stripping any decimals.
> 1 votes

# Answer
# Risky, 12 bytes

```
+/+2}/??+_0{11111111111

```

Try it online!

Takes a string, since Risky doesn't support real numbers.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 11 bytes

```
IntegerPart

```

Try it online!
> 0 votes

# Answer
# Ohm v2, 1 byte

```
ì

```

Try it online!
> 0 votes

# Answer
# MathGolf, 1 byte

```
i

```

Try it online!

Casts the input to integer, using Python's `int`. As easy as it gets.
> 0 votes

# Answer
## IBM/Lotus Notes Formula, 11 bytes

```
@Integer(i)

```

Takes input from a form field `i`. Only posted because of the fun feature that given a list the formula will be applied to all members of the list without the need of a `@For` loop and also because I haven't posted a Notes Formula answer for a while.

There is no online interpreter for Formula language so a screenshot showing output for all given test cases is the best I can do.
> 0 votes

# Answer
# x86-64 Machine Code (Windows), 5 bytes

```
F3 0F 2C C0          cvttss2si   eax,xmm0
C3                   ret

```

`cvttss2si` \- Convert with truncation scalar single to integer.
> 0 votes

# Answer
# Pyth, 1 byte

```
s

```

Try it online!

Equivalent of Python's `int(i)` with implicit input and output.
> 0 votes

# Answer
# T-SQL, 16 bytes

Shorter than `cast(@ as int)`

```
DECLARE @ DECIMAL(10,5)=-11.7
PRINT str(@-@%1)

```

Can save 5 bytes by removing `str()` if output like `-11.00000` is allowed
> 0 votes

# Answer
# Befunge-93, 3 bytes

```
&.@

```

Try it online!
> 0 votes

# Answer
# Rust, 10 bytes

```
f64::trunc

```

Try it online!

Rustdoc of `f64::trunc`.
> 0 votes

# Answer
# Pascal (FPC), 44 bytes

```
function b(a:Real):Real;begin b:=Int(a);end;

```

Try it online!
> 0 votes

# Answer
# Oracle SQL, 23 bytes

```
select x-mod(x,1)from t

```

Try it online!
> 0 votes

# Answer
# C (clang), 15 bytes

```
f(i){return i;}

```

Try it online!

For some reason, this doesn't work with GCC. Also, in real life, because C allows implicit conversion between `float`s and `int`s (which is being exploited in this function), you sometimes wouldn't have to write any code at all to round something towards zero. And that fact is probably used in a lot of C answers on Code Golf.
> 0 votes

# Answer
# Runic Enchantments, ~~13~~ 5 bytes

```
i'.A@

```

Try it online!

Now that the `A` command supports `Trunc(x)`, the answer now works on `0` as input and is shorter, as it no longer needs to jump through hoops to determine the input's sign.
> 0 votes

# Answer
# Emacs Lisp, 9 bytes

```
'truncate
```

Try it online!
> 0 votes

# Answer
# Kotlin, 9 bytes

```
x.toInt()

```

There’s also `truncate()` function which is longer in bytes.
> 0 votes

# Answer
# TI-BASIC (2 bytes)

```
iPart(Ans

```

Hex dump:

```
B9 72

```

**Explanation:**

`iPart(` truncates its parameter.

**Examples:**

```
-5.2
            -5.2
iPart(Ans
              -5
5.2
             5.2
iPart(Ans
               5

```
> 0 votes

# Answer
# Commodore BASIC (C64/128/TheC64Mini, Commodore PET, VIC-20, C16/+4) 37 tokenized and BASIC bytes used

```
 0inputa:a%=abs(a):ifa<.thena%=-a%
 1?a%

```

Example input/output:

```
 1.99 /  1
-1.99 / -1

```

When converting a numeric value to an integer by declaring a `%` variable, it zero-fills the bytes after the decimal point, so `1.99` becomes `1.0` on the variable stack; `-1.99` will become `-2` so I have corrected this in line `0` with the `if/then` statement.
> 0 votes

# Answer
## Visual Basic Script, 3 bytes

```
Fix

```

### Full program, 20 bytes

```
MsgBox Fix(InputBox)

```
> 0 votes

# Answer
# x86 machine code (non-trivial), 22 bytes

A routine that rounds an IEEE 754 floating point number in `eax`.

```
00000000: c1c8 1788 c180 e97f 7902 31c0 d3c0 80e9  ........y.1.....
00000010: 17f6 d9d3 e0c3                           ......

```

Try it online! (This wraps the routine sans the final ret in a C++ asm block to make testing easy).

It works by clearing all the bits in the mantissa after the point (just like how you would do it with decimal numbers).

Some examples to show what I mean:

```
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
0 10000000 10001100110011001100110 ; ~  3.1, exp = 1
0 10000000 10000000000000000000000 ; =  3.0

0 10000101 10010101100110011001101 ; ~101.4, exp = 6
0 10000101 10010100000000000000000 ; =101.0

```

Annotated source (NASM format):

```
[BITS 32]
; 64 bit also works

; truncates an IEEE 754 float in %eax to an integer.
; modifies %eax and %cl
rtz:
    ; circular shift right the float by 23 bits
    ; (size of the mantissa) so the exponent is in al.
    ror eax,23
    ; then put it in cl.
    mov cl,al
    ; subtract 127 from the exponent value to get the
    ; true exponent.
    sub cl,127
    ; if the result is positive, skip the 0 step.
    jns noZero
    ; if the result is negative, then the exponent is
    ; also negative - i.e. the magnitude of the input
    ; is less than 1 - so the result should be 0.
    xor eax,eax
noZero:
    ; circular shift left the float by %cl bits
    ; (the exponent) to truncate the mantissa.
    rol eax,cl
    ; calculate 23 - cl, how many bits we need to
    ; shift back left to realign the float.
    sub cl,23
    neg cl
    ; logical shift left the float by %cl bits.
    ; this zero fills, so the mantissa is truncated.
    shl eax,cl
    ret

```
> 0 votes

# Answer
# Japt `-h`, 1 byte

```
õ

```

Try it here
> 0 votes

# Answer
# Lua, 30 bytes

```
print(((...):gsub('%..*','')))

```

Try it online!

Unfortunately the integer division operator rounds towards negative infinity... so instead we remove the decimal from the string representation of the input.
> 0 votes

# Answer
# Thunno 2, 1 byte

```
N

```

Attempt This Online!

Leaves only the integer part.
> 0 votes

# Answer
# J-uby, 1 byte

In J-uby `Z` is an alias for `:to_i`.

```
Z

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, number, rational-numbers
---


title: Summation from a to b

text:
# Question
Title: Summation from a to b
The program has an input of a and b, and outputs the sum of numbers from a to b, inclusive. Score is in bytes. As always, standard loopholes are disallowed.

If your input is in the format \[a,b\], +3 bytes

# Answer
# Stuck, 4 Bytes

I'm amazed Stuck finally is winning something! The inclusive range function checks to see if the top of the stack is a list of length 2, and uses it for the parameters of the range function if so.

```
t]R+

```

Input is `|` separated, as `t` takes a bunch of inputs separated by `|`s and places them on the stack. `]` just wraps the elements in a list, and lets the range function do it's job.

If that still falls in the penalty, then this works (5 Bytes): `ii]R+`
> 24 votes

# Answer
# Pyth, ~~6~~ ~~4 bytes + 3 = 7~~ 5 bytes

```
s}vzQ

```

Avoids the 3-byte penalty imposed by the new input requirements via an extra byte.

Takes input separated from stdin separated by newlines.

Live demo.
> 13 votes

# Answer
## Python, 26

```
lambda a,b:(a+b)*(b-a+1)/2

```

Assumes `b>=a`. Uses the formula of `mean * #summands`. The result is a whole number, so it doesn't matter if the `/` is Python 2's floor division.

Shorter by 2 chars than the direct expression

```
lambda a,b:sum(range(a,b+1))

```
> 10 votes

# Answer
# Matlab/Octave, 14 bytes

```
@(a,b)sum(a:b)

```
> 8 votes

# Answer
# Julia, 15 bytes

```
s(a,b)=sum(a:b)

```

This creates a function `s` that sums the range `a:b`. This assumes `a``b`.
> 8 votes

# Answer
# Dyalog APL, ~~8~~ 7 bytes

```
+÷2÷1--

```

This is a dyadic function train which is equivalent to

```
{(⍺+⍵)÷2÷1-⍺-⍵}

```

Try it online.

### How it works

```
        ⍝ Left argument: a, right argument: b
      - ⍝ Calculate a-b.
    1-  ⍝ Subtract the difference from 1 to calculate 1-(a-b) = b-a+1.
  2÷    ⍝ Divide 2 by the difference to calculate 2/(b-a+1).
+       ⍝ Calculate a+b.
 ÷      ⍝ Divide the sum by the quotient to calculate (a+b)/(2/(b-a+1)),
        ⍝ i.e., (a+b)(b-a+1)/2.

```
> 8 votes

# Answer
# Javascript ES6, 21 bytes

```
a=>b=>(a+b)*(b-a+1)/2

```

Used the same approach to that problem that's almost everywhere: "Add up all of the numbers between 1 and 100, inclusive."
> 7 votes

# Answer
# Java, ~~44~~ 42 bytes

An approach I haven't seen here so far: Via gaussian sums you can derive that the sum of all numbers from `a` to `b` is `(b-a+1)*(b+a)/2`

If you only have to implement a function, you could do it in 42 bytes:

```
int s(int a,int b){return(b-a+1)*(b+a)/2;}

```

The conventional approach is 3 bytes longer:

```
int s(int a, int b){for(;b>a;a+=b--);return a;}

```

A full program is 142 bytes:

```
public class S{public static void main(String[]a){int n=Integer.parseInt(a[0]),m=Integer.parseInt(a[1]);System.out.println((m-n+1)*(m+n)/2);}}

```
> 6 votes

# Answer
# APL, 9 bytes

```
-⍨/2!⎕+⍳2

```

Takes input as a two-element list . Set your index origin to 0 (`⎕IO←0`) before running.

This is longer than the answer by @Dennis but in my opinion more stylish.

It calculates `(B+1 nCr 2)-(A nCr 2)` = `B(B+1)/2-A(A-1)/2`.
> 6 votes

# Answer
# TI-BASIC, 8 bytes

```
mean(Ans+Ansmin(ΔList(Ans

```

Takes input in the form `{A,B}`.

```
                      Ans    ; {A,B}
                ΔList(       ; {B-A}
            min(             ;  B-A
         Ans                 ; (B-A)*{A,B}
     Ans+                    ; (B-A+1)*{A,B}
mean(                        ; (B-A+1)*(A+B)/2

```

By comparison, the shortest two-variable solution is 11 bytes:

```
Prompt A,B
sum(randIntNoRep(A,B   ;random permutation of integers between, inclusive

```
> 6 votes

# Answer
## SH, 16 bytes

```
seq $1 $2|numsum

```

Where $1 and $2 are the values of two args passed to this program on the command line. numsum is from the num-utils package. Another version that is also 16 bytes is:

```
seq -s+ $1 $2|bc

```
> 6 votes

# Answer
## CJam, 7 bytes

```
q~),>:+

```

Test it here.

```
q~  e# Read and eval input, pushing a and b onto the stack.
),  e# Increment b and turn into the range [0 1 2 ... b-1 b].
>   e# Discard the first a elements to get [a a+1 ... b-1 b].
:+  e# Reduce + onto the list, computing the sum.

```
> 5 votes

# Answer
## Mathematica, 9 bytes

```
Tr@*Range

```

This evaluates to an unnamed function taking two integers. I was going to use the built-in `Sum`, but it's 4 bytes longer:

```
x~Sum~{x,##}&

```
> 5 votes

# Answer
## \>\<\>, 14 bytes

This assumes that the stack has already been populated with `a` and `b`, so this is basically a function. I'm using this online interpreter which lets you put values onto the stack before the program runs. An extra three bytes for `-v` (plus a space, for running from a terminal) would put this answer at **17 bytes**.

```
:r:@-1+@+*2,n;

```

### Explanation:

```
-v  ab                 (initial stack)
:   abb                duplicates top of stack (b)
r   bba                reverses stack
:   bbaa               duplicates top of stack (a)
@   baba               rotates top three elements clockwise (baa -> aba)
-   ba,(b-a)           subtraction (ba -> b-a)
1+  ba,(b-a+1)         adds 1 (b-a -> b-a+1)
@   (b-a+1),ba         rotates top three elements clockwise
+   (b-a+1),(b+a)      addition (ba -> b+a)
*   (b-a+1)*(b+a)      multiplication
2,  (b-a+1)*(b+a)/2    division by 2 (/ is a mirror, so , is used instead)
n;  <integer, quit>    output top of stack as an integer and quit

```

This assumes that `0 <= a <= b` and uses this closed-form solution `(b-a+1)(b+a)/2` to directly calculate the answer.

---

This code below goes the route of trying to be a full program, but only works for `0 <= a <= b <= 9`. That you have to do integer parsing in \>\<\> is annoying. Thanks to **Cole**, if we assume the input is two single digits, then four bytes can be shaved off. **20 bytes.**

```
ic%:ic%:@$-1+@+*2,n;

```

The trick is that instead of `68*-`, use `c%` (take the modulus with respect to `12`). This will indeed work because `48+x (mod 12)` is `x (mod 12)`, which is 0-9 if `x` is 0-9.
> 5 votes

# Answer
# R - 24 Bytes

```
f=function(a,b) sum(a:b)

```
> 5 votes

# Answer
# Haskell, 13 bytes

```
x#y=sum[x..y]

```

Usage example: `10 # 12` -\> `33`
> 4 votes

# Answer
# O, ~~8~~ 7 bytes

```
Hjmr]+o

```

Explanation

```
H   Start an array with a number from input
 j  Get input as number
 mr Range between
]
+   Sum the array
o   print it

```

Try it here
> 4 votes

# Answer
# Brain-Flak, ~~32~~ 30 bytes

```
([{({}[()])}{}]{()({}[()])}{})

```

Try it online!

## Explanation

This uses the triangulation algorithm to calculate `T(a-1)` and `T(b)` then pushes the difference. I actually golfed 2 bytes off the existing world record triangulation algorithm while making this solution.

To push `T(a-1)` it uses a modified version of the original algorithm. Instead of the simple:

```
({}[()])({()({}[()])}{})

```

I removed both the first `({}[()])` and the `()`.

The reason `()` was there in the first place was that `({({}[()])}{})` quite conveniently calculates `T(n-1)` for us so there is no need to decrement if we remove the `()`

This first portion is made negative and put next to the second portion which performs standard triangulation inside of the outer push.

```
([{({}[()])}{}]{()({}[()])}{})

```
> 4 votes

# Answer
# PowerShell, ~~32~~ ~~31~~ 29 Bytes

```
$args-join'..'|iex|measure -s

```

Thanks to TessellatingHeckler for the alternate way to make a range and sum it. Works for any combination of `a` and `b` so long as the difference between them is less than 50,000.

---

Previous version (31):

```
param($a,$b)($b-$a+1)*($b+$a)/2

```

Uses the same formula as others, assumes that `b>=a`.

---

Previous version (32):

```
param($a,$b)($a..$b)-join'+'|iex

```

Pretty trivial. Generates a range of numbers from `$a` to `$b`, `-join`s them with a `+`, then pipes that to `Invoke-Expression` which performs the summation. Yay verbosity. *Note:* This function will break if the two numbers are \> 50,000 apart, as that's the (hard-coded) limit of dynamically generated ranges in PowerShell, *but* it correctly handles `b<a`, so, y'know...
> 3 votes

# Answer
## Befunge-93, ~~18~~ 16 bytes

```
&:1-*&:1+*\-2/.@

```

### Explanation

```
&   a                      input as integer (a)
:   aa                     duplicate top of stack (a -> a,a)
1-  a,(a-1)                subtract 1 from top of stack (a -> a-1)
*   a*(a-1)                multiply top two values of stack (a,a-1 -> a*(a-1))
&   a*(a-1),b              input as integer (b)
:   a*(a-1),bb             duplicate top of stack (b -> b,b)
1+  a*(a-1),b,(b+1)        add 1 to top of stack (b -> b+1)
*   a*(a-1),b*(b+1)        multiply top two values of stack (b,b+1 -> b*(b+1))
\   b*(b+1),a*(a-1)        swap top two values of stack (c,d -> d,c)
-   b*(b+1)-a*(a-1)        subtract top two values of stack (d,c -> d-c)
2/  (b*(b+1),a*(a-1))/2    divide top of stack by 2
.@  <output, exit>         output as integer and stop

```

This uses the following formula:

```
b(b+1)   (a-1)(a-1+1)   b(b+1) - a(a-1)
------ - ------------ = ---------------
  2            2               2

```

Unfortunately, the shorter `(b-a+1)(b+a)/2` cannot be done in Befunge easily because it requires accessing `b` and `a` twice, which is impossible to do when working only with the top two values of the stack. Storing a value in "memory" would take more characters.
> 3 votes

# Answer
# C++, 42 bytes

As a function (42 bytes):

```
int s(int a,int b){return(a+b)*(b-a+1)/2;}

```

As a full program that reads from STDIN and writes to STDOUT (86 bytes):

```
#include<iostream>
main(){int a,b;std::cin>>a;std::cin>>b;std::cout<<(a+b)*(b-a+1)/2;}

```

Both approaches compute the sum using the Gaussian formula.

Ungolfed:

```
#include <iostream>

int s(int a, int b) {
    return (a + b) * (b - a + 1) / 2;
}

int main() {
    int x, y;
    std::cin >> x;
    std::cin >> y;
    std::cout << s(x, y) << std::endl;
    return 0;
}

```

Try it online
> 3 votes

# Answer
# Rust, 27 bytes

Creates a closure `s` that takes two unsigned 8-bit integers and returns another.

```
let s=|m,n|(n-m+1)*(m+n)/2;

```
> 3 votes

# Answer
# Jelly, 2 bytes

```
rS

```

Try it online.

```
r   Yields inclusive range [a, b]
 S  Sum

```
> 3 votes

# Answer
# Java, 19 bytes

```
a->b->a-a*a-b*~b>>1

```

*Thanks to ceilingcat*

Try it online!

## Explanation

Expand the numerator:

$$(a+b)\*(b-a+1) = a\*b - a\*a + a + b\*b - a\*b + b = b * b - a * a + a + b$$

`>> 1` is equivalent to divide by `2`, but it has lower precedence than addition and subtraction, so no parentheses are required. `~x` is the same as `-x - 1`. Thus,

```
a-a*a-b*~b>>1 = (a-a*a-b*(-b-1))/2
              = (a-a*a+b*b+b)/2
              = (b*b-a*a+a+b)/2

```

# Java, 21 bytes

```
a->b->(a+b)*(b-a+1)/2

```

Try it online!
> 3 votes

# Answer
# Awk, 24 bytes

`$0=""($1+$2)*($2-$1+1)/2`

Incorporated manatwork's suggestion.
> 2 votes

# Answer
# Applescript, ~~147~~ 137 Bytes

Welp. I'm not winning.

```
set a to(text returned of(display dialog""default answer""))
set b to(text returned of(display dialog""default answer""))
(b-a+1)*(b+a)/2

```

Since I'd never seen an Applescript answer before, I decided I'd make one, then immediately realized why it never had been done.

The explanation is fairly straightforward -

```
set ... to (text returned of (display dialog "" default answer ""))
            ^
            Get the text of                     ^ the user inputs an answer here

(b-a+1)*(b+a)/2
^ with nothing else below this, Applescript recognizes it as the final
  value and prints to console.

```
> 2 votes

# Answer
# PHP, 29 bytes

Based on standard stricks to set variables (eg register\_globals oldSkool)

```
while($b>=$a)$r+=$b--;echo$r;

```
> 2 votes

# Answer
# R, 18 Bytes

```
sum(scan():scan())

```
> 2 votes

# Answer
# Groovy, 19 Bytes

```
{a,b->(a..b).sum()}

```
> 2 votes

# Answer
# 05AB1E, 2 bytes

```
ŸO

```

Explanation:

```
      # Implicit input
      # Implicit input
  Ÿ   # Push [a...b]
   O  # Sum list
      # Implicit print

```

Try it online!
> 2 votes

# Answer
# Vyxal `s`, 1 byte

Try it Online! (2 bytes flagless)

Explanation:

```
ṡ  # Push the range from a to b
   # s flag sums the top of the stack
   # Implicitly print

```
> 2 votes

# Answer
# Ruby, 22 bytes

```
->a,b{eval [*a..b]*?+}

```

Just as long as using the expression in @xnor's Python answer:

```
->a,b{(a+b)*(b-a+1)/2}

```

Test it:

```
->a,b{eval [*a..b]*?+}[10,20] #=> 165

```
> 1 votes

# Answer
# Math++, 23 bytes

```
?>a
?>b
(b-a+1)*(b+a)/2

```
> 1 votes

# Answer
# Squirrel, 21 bytes

```
@(a,b)(b-a+1)*(b+a)/2

```

Creates an anonymous function.
> 1 votes

# Answer
### , 19 bytes

```
   f=:4 :'+/x+i.1+y-x'
   1 f 1
1
   1 f 2
3
   5 f 10
45

```

It would be longer if it calculated the answer directly, because it would need some parentheses. I can't quickly find a builtin way to "range from a to b", so it does:

```
                    # The parameters are x on the left, y on the right
f=:4 : '            # f is a dyad verb defined as...

 +/                  # The sum of ...
   x +               # x added to the list of ...  (turns 0 1.. to x x+1..)
       i.            # the integers from 0 to ...
          1+y-x      # 1 + y -x                    (sequence length)

'                    # end definition string.

5 f 10 ->

1 + 10 - 5 =
6

i. 6 =
0 1 2 3 4 5

5 + 0 1 2 3 4 5 =
5 6 7 8 9 10

+/ 5 6 7 8 9 10 =
5 + 6 + 7 + 8 + 9 + 10 =
45

```
> 1 votes

# Answer
# PHP, 39 bytes

As usual not even close to the shortest answer:

```
<?=array_sum(range($argv[1],$argv[2]));

```

Runs from command line like:

```
php sum.php 10 20

```
> 1 votes

# Answer
## Swift 2, 27 bytes

Swift seems to be able to infer types much more easily these days...

`let f={($0+$1)*($1-$0+1)/2}`

Called with `f(a, b)`
> 1 votes

# Answer
## C++11 lambda, 37 bytes

```
[&b](int a,int&b){b=(a+b)*(b-a+1)/2;}

```

Invocation:

```
int main()
{
    int a,b;
    std::cin >> a; std::cin >> b;
    std::cout << ([&b](int a,int&b){b=(a+b)*(b-a+1)/2;}(a,b),b) << std::endl;
    return 0;
}

```
> 1 votes

# Answer
## Perl 6 (14 chars / bytes)

The only obvious solution is to create a list from `a` to `b`, and then to reduce it with the addition operator.

```
[+] a..b

```

That would be a snippet, so let's place it in a pointy block.
( One of the ways to create a lambda expression. )

```
-> \a, \b { [+] a..b } # 22 chars

->\a,\b{[+] a..b} # 17 chars

```

Or better yet use a placeholder parameterized block.

```
{[+] $^a..$^b} # 14 chars

```

Examples of it's use:

```
say {[+] $^a..$^b}(4,7) # 22␤

# store it as a subroutine and in a scalar
my &s = my $s = {[+] $^a..$^b};

say s 4,8; # 30␤
say $s.(3,8); # 33␤

say ( {[+] $^a..$^b} for 4,7, 4,8, 3,8, ); # (22 30 33)␤

```

---

If you wanted to be cheap, you could modify the parser by adding a list summation operator. Which technically could be considered a new language at that point. Although that would be a made up language so wouldn't be a valid answer anyway.
( This is actually how it might be written in the Rakudo implementation if it was added )

```
sub prefix:<∑> (+@a) is looser(&[,]) {
  [+] @a
}

### new language starts here ###

{∑$^a..$^b} # only 11 chars / 12 bytes in UTF8

```

( Scoring it with bytes feels wrong because Perl 6 and thus this new anonymous language only deal with graphemes in strings. )
> 1 votes

# Answer
## Minkolang 0.8, 14 bytes (INVALID)

Minkolang was created after this challenge was posted, so I post this answer only in the sense of contributing to a catalog.

```
nndr-[d1-]$+N.

```

### Explanation

```
n     input as integer (stack: a)
n     input as integer (stack: a,b)
d     duplicate top of stack (stack: a,b,b)
r     reverses stack (stack: b,b,a)
-     subtraction (stack: b,b-a)
[     starts a For loop that will run b-a times
 d    duplicates top of stack
 1-   subtracts 1
]     closes For loop (stack: b,b-1,b-2,...,a+1,a)
$+    sums the stack
N.    outputs as integer and stops

```

Try it here.

---

The formula-based solutions like what I used in my Befunge and \>\<\> answers are 2 and 3 bytes longer, respectively:

```
nd1-*nd1+*r-2:N.
ndnd3R-1+1R+*2:N.

```
> 1 votes

# Answer
# Jolf, 4 bytes

Try it here!

```
usjJ
u    sum of
 s   the inclusive range between
  jJ two inputs

```
> 1 votes

# Answer
# jq, 25 characters

(24 characters code + 1 character command line option)

```
[range(.[0];.[1]+1)]|add

```

Sample run:

```
bash-4.3$ jq -s '[range(.[0];.[1]+1)]|add' <<< '10 15'
75

```

## jq, 27 characters

(24 characters code + 3 character penalty)

```
[range(.[0];.[1]+1)]|add

```

Sample run:

```
bash-4.3$ jq '[range(.[0];.[1]+1)]|add' <<< '[10,15]'
75

```

On-line test

Not specifically interesting, just the `-s` option which comes handy here: it interprets raw input as array. (Yes, the code itself is identical in both solutions.)
> 1 votes

# Answer
# PlatyPar, 2 bytes

```
_s

```

Try it online!
> 1 votes

# Answer
# Lua, 40 Bytes

Used the same method as the Javascript answer, but in Lua.

```
function y(a,b)return(a+b)*(b-a+1)/2 end

```

You use this as such

```
y(3, 6) --3 + 4 + 5 + 6 == 18

```
> 1 votes

# Answer
# K (oK), ~~14~~ 12 bytes

**Solution:**

```
+/^/!:'|0 1+

```

Try it online!

**Examples:**

```
> +/^/!:'|0 1+2 7
27
> +/^/!:'|0 1+5 10
45

```

**Explanation:**

Slightly different to doing `.5*(x+y)*1+y-x`. Instead, calculate ranges, take largest except smallest and then sum up:

```
+/^/!:'|0 1+ / solution
        0 1+ / vectorised addition of 0 1 / 2 7 -> 2 8
       |     / reverse:                   / 2 8 -> 8 2
    !:'      / til (!:) each (')          / (8;2) -> (0 1 2 3 4 5 6 7;0 1)
  ^/         / except (^) over (/)        / (0 1 2 3 4 5 6 7;0 1) -> 2 3 4 5 6 7
+/           / add (+) over (/) aka sum   / 2 3 4 5 6 7 -> 27

```
> 1 votes

# Answer
# J-uby, 9 Bytes

```
:!~|:/&:+

```

Explanation:

```
:!~         generate range a..b
   |        then
    :/&:+   sum it together

```

Expansion:

```
:!~|:/&:+
->(a,b){ (:/&:+).(a!~b) }
->(a,b){  :+ / (a !~ b) }
->(a,b){ (a..b).reduce(:+) }

```
> 1 votes

# Answer
# Bash \+ bc, 13 bytes

Even shorter bash solution:

```
seq -s+ $@|bc

```

Try it online!

### Explanation

`seq -s+ $@` called with for example `2 7` prints `2+3+4+5+6+7`, this gets piped to `bc` which evaluates it & prints the result.
> 1 votes

# Answer
# Symbolic Python, 49 bytes (46 + 3 penalty)

```
_=(_[_==_]*-~_[_==_]-_[_>_]*~-_[_>_])/-~(_==_)

```

**Try it online!**

Anything involving `range`, `len`, or loops would be too difficult in Symbolic Python, and so I decided the easiest way was to use the formula:

$$ \sum\_{r=a}^b r = \frac{b(b+1) - a(a-1)}{2} $$
> 1 votes

# Answer
# 33, 20 bytes

```
OcaxcmszOcaxaclaz2do

```

Try it online!

## Explanation

This answer uses the following formula to calculate it: $$a + (a+1) + (a+2) + \cdots + b = {a-a^2+b+b^2 \over 2}$$

```
O       O            | Get a and b as two integers delimited by whitespace
 ca                  | (a                  )
   xcm               | (  - a^2            )
      sz      la     | (        + (       ))
         ca          | (          (b      ))
           xac       | (          (  + b^2))
                z2d  | (                   ) / 2
                   o | Print it

```
> 1 votes

# Answer
# APL(NARS), 8 chars, 16 bytes

```
{+/⍺..⍵}

```

test:

```
  f←{+/⍺..⍵}
  1 f 2
3
  2 f 10
54

```

This it is 6 chars but I not find a way to assign a name to it

```
+/↑../

```

Using as function 2 3
> 1 votes

# Answer
## Reg (a.k.a Unofficial Keg), 17 bytes

Try it online behavior is unknown.

```
¿¿ï_'(:|_)(+).

```

This takes 2 inputs separated by newlines.
> 1 votes

# Answer
## Keg, 7 bytes (SBCS is on Keg wiki)

```
¿¿ɧ∑+).

```

Explanation

```
¿¿#      Two nice inputs
  ɧ#     Generate range
   ∑+)#  Summation (looks quite weird because ∑ translates to (!;|. )
      .# Output as integer

```

TIO
> 1 votes

# Answer
# Desmos, 21 bytes

```
f(a,b)=(a+b)(b-a+1)/2

```

Try It On Desmos!
> 1 votes

# Answer
# Alice, 23 bytes

```
/@M\-:2*t.{
\MO/.h*2:~{

```

Try it online!

## Flattened

```
/MM/.h*2:~.t*2:-\O@
/                      Switch to Ordinal
 MM                    Read the two command line arguments
   /                   Back to cardinal
    .h*2:              (a*a+1)/2, the sum of all the integer between 0 and a
         ~             Swap the stack values
          .t*2:        (b*b-1)/2, the sum of all the integer between 0 and b-1
               -       Diff between the two sums
                \      Switch to Ordinal
                 O     Print the result to the output
                  @    Bye

```
> 1 votes

# Answer
# Knight, 19 bytes

```
O/*+E=aP=bP+1-b a 2

```

Try it online!

Uses the formula `(a+b)*(b-a+1)/2`.
> 1 votes

# Answer
# Factor \+ `math.unicode`, 12 bytes

```
[ [a,b] Σ ]

```

Try it online!

Interesting tidbit: `sum` (and therefore `Σ`) is a generic (polymorphic) word that specializes on `range`s to efficiently calculate arithmetic sums.
> 1 votes

# Answer
## C, ~~32~~ 28 bytes

```
f(a,b){a=a==b?a:a+f(a+1,b);}

```

**Easier to read**

```
int f(a,b){

  // This ends the recursion by returning the current number
  if(a == b) return a;

  // This recursively returns the sum of the
  // current low number and the next low number.
  return a + f(a+1,b);
}

```
> 1 votes

# Answer
# C preprocessor, 40 bytes

`#define S(a,b) (((a)+(b))*((b)-(a)+1)/2)`
> 0 votes

# Answer
# Bash/GNU, 21 Bytes

```
expr `seq -s" + " $@`

```

called with arguments `a` and `b`

* `seq` generates a sequence from `a` to `b`, separated by " + "
* `expr` evaluates and prints the resulting expression
> 0 votes

# Answer
# gs2, 5 bytes

```
WÉ'Od          57 90 27 4f 64

```

Read two numbers, dump them on the stack, increment the top one, take the range between them, sum it.
> 0 votes

# Answer
# Hassium, 60 Bytes

```
func main(){s=0;for(x=input();x<=input();x++)s+=x;print(s);}

```

Run online and see expanded here
> 0 votes

# Answer
## Burlesque - 6 bytes

`per@++` usage:

```
$ echo "10 20" | blsq --stdin "per@++"
165

```
> 0 votes

# Answer
# DUP, 15 bytes

```
[^^+^3ø-1+*2/.]

```

`Try it here!`

Anonymous lambda. Usage:

```
1 10[^^+^3ø-1+*2/.]!

```

# Explanation

Uses the formula `(a+b)*(b-a+1)/2`.
> 0 votes

# Answer
## Elixir, 37 bytes

```
fn(a,b)->Enum.reduce(a..b,0,&+/2)end

```

poster child example for reduce, i guess. allows b \> a.
> 0 votes

# Answer
## Seriously, 5 bytes

```
,u,xΣ

```

Try it online!
> 0 votes

# Answer
# Pylons, 3 bytes

`iks`

How it works:

```
i # Take command line input.
k # Push the inclusive range(stack[-2]..stack[-1])
s # Sum the stack.

```
> 0 votes

# Answer
# Forth, 27 bytes

```
0
: f 1+ SWAP DO I + LOOP ;

```

The parameters much be pushed smallest first. Run like this:

```
1 4 f .

```

**Try it online**
> 0 votes

# Answer
# J, 11 bytes

```
-:@<:@-*-@+

```

This is a tacit verb. Example usage:

```
    v =: -:@<:@-*-@+
    5 v 10
45

```

This verb is a fork of three verbs: `-:@<:@-`, `*`, and `-@+`. A fork `x (f g h) y` is equivalent to `(x f y) g (x h y)`. Thus, `x (-:@<:@-*-@+) y` = `(x(-:@<:@-)y) * (x (-@+) y)`. Likewise, the composition of two verbs `x (f @ g) y` equals `f (x g y)`. Using this rule, given that `<:` decrements, and `-:` divides its argument by two, `x(-:@<:@-)y = (x - y - 1)/2` and `x(-@+)y = -(x+y)`. Therefore `x(-:@<:@-*-@+)y = (x - y - 1) / 2 * -(x+y)`, and by moving the sign from `-(x+y)` to `(x-y-1)`, we get `(y - x + 1) / 2 * (x + y)`.
> 0 votes

# Answer
## QBIC, 15 bytes

```
::[a,b|d=d+c]?d

```

`::` takes two command line parameters and names them `a` and `b`. Then, we create a `FOR` loop (using iterator `c`) from `a` to `b`. We keep adding `c` to `d`, then print `d` and exit.
> 0 votes

# Answer
# Detour, 11 bytes

```
{+(}-!>)*d.

```

This uses the `(a+b)*(b-a+1)/2` formula.

`+` encodes `(a+b)`, `-!>` encodes `(b-a+1)` (really `-(a-b)+1`), and `*d.` multiplies (`*`) the two together, halves it (`d`), and outputs it (`.`). `{…}` makes two copies of a and b and `(…)` manipulate where the two copies go so that the result of `(a+b)` doesn't get fed into the `(b-a+1)` section.

Try it online!
> 0 votes

# Answer
# Proton, 17 bytes

```
a=>b=>sum(a..b+1)

```

Try it online!
> 0 votes

# Answer
# Japt, 4 bytes

Input order is irrelevant.

```
òV x

```

Test it
> 0 votes

# Answer
# TI-Basic, 14 bytes

```
Input :.5(YY+Y+X-XX

```

Bonus: no lists or list commands.
> 0 votes

# Answer
# Perl 5, 19 bytes

18 bytes of code + 1 for `-p`

```
map$\+=$_,$_..<>}{

```

Try it online!
> 0 votes

# Answer
# Excel, 20 bytes

```
=(B1^2+B1-A1^2+A1)/2

```
> 0 votes

# Answer
# Husk, 2 bytes

```
Σ…

```

Try it online!

### Explanation

```
    -- implicit inputs: A B   |  2 7
 …  -- inclusive range [A,B]  | [2,3,4,5,6,7]
Σ   -- sum                    |  2+3+4+5+6+7  == 27

```
> 0 votes

# Answer
# RProgN 2, 2 bytes

```
R+

```

Boring solution, Range from a to b, then sum.

Try it online!
> 0 votes

# Answer
# Casio Basic, 20 bytes

```
sum(seq(x,x,a,b))

```

Simple function. 17 bytes for the program, 3 bytes to enter `a,b` as arguments.
> 0 votes

# Answer
# LOLCODE, 184 bytes

```
HAI 1.3
I HAS A B
I HAS A J
GIMMEH J
I HAS A Q
GIMMEH Q
MAEK Q A NUMBR
IM IN YR L UPPIN YR i TIL BOTH SAEM DIFF OF Q AN SUM OF i AN J AN -1
	VISIBLE SUM OF i AN J
IM OUTTA YR L
KTHXBYE

```

Try it online!
> 0 votes

# Answer
# Python 2, 28 bytes

```
lambda x,y:sum(range(x,y+1))

```

Try it online!
> 0 votes

# Answer
# Japt `-x`, 3 bytes

```
Nrò

```

Try it online!

# Explanation

I use `N` to avoid the `+3` input penalty.

I would normally format the input as \\$\[a,b\]\\$ and my code would be .

`N` reads the entire input.

`r` reduces that by: `ò`, which creates the range from \\$a\\$ to \\$b\\$.

`-x` sums the output.
> 0 votes

# Answer
# Alchemist, 135 bytes

```
_+a->
0_+0m+a+b->u+x+v+y
0m+0a+b->v+y
0a+0b+0m+u+v->m
0a+0b+0m+0u+v->m
m+u+v->a+b+m
m+0u+v->b+m
m+0u+0v->
0a+0b+x+y->
0a+0b+0x+y->Out_I

```

Output in unary, try it online or view the remaining \\$\texttt{y}\\$-atoms here!

## Explanation

Pretty similar to this answer, uses that \\$a \leq b\\$: Basically we ensure with `0_` on the second rule that the first rule must always be applied first (initially the universe always contains one \\$\texttt{\_}\\$-atom), removing one \\$\texttt{a}\\$-atom and then summing both \\$\texttt{#x} = \[1\dotsc \texttt{#a}\]\\$ and \\$\texttt{#y} = \[1\dotsc \texttt{#b}\]\\$ in parallel, once there are no \\$\texttt{a}\\$\- or \\$\texttt{b}\\$-atoms left, we subtract them and finally print the remaining \\$\texttt{y}\\$-atoms.

## Ungolfed

```
# Remove one a-atom:
_+a->
# Sum [1..#a] (to out_a) and [1..#b] (to out_b) in parallel:
0_+0mov+ a+b->u+out_a+v+out_b
0mov+0a+b->v+out_b
0a+0b+0mov+ u+v->mov
0a+0b+0mov+0u+v->mov
mov + u+ v->a+b+mov
mov +0u+ v->b+mov
mov +0u+0v->
# If we're done with that:
0a+0b+ out_a+out_b->         # difference: out_b - out_b
0a+0b+0out_a+out_b->Out_I    # output rest in unary

```
> 0 votes

# Answer
# JavaScript, 21 bytes

Input is taken in currying syntax: `f(a)(b)`

```
a=>b=>b*b-a*a-(a+b)*2

```

Try it online!
> 0 votes

# Answer
# Stax, 4 bytes

```
╖c╟Y

```

Run and debug it
> 0 votes

# Answer
# Pip, 13 bytes

```
Fia\,q{Yy+i}y

```

Attempt This Online!

Can't find a "sum" operator in Pip's documentation.

#### Explanation

```
Fia\,q{Yy+i}y  # Implicit input. A on the command line, B on STDIN.
  a\,q         # Inclusive range, A to B
Fi    {    }   # Loop through, with variable i:
        y+i    #  Add i to y (implicitly defaults to 0)
       Y       #  And store the result in y
            y  # After the loop, push y
               # Implicit output.

```
> 0 votes

# Answer
# Pyt, 3 bytes

```
⇹ŘƩ

```

Try it online!

```
⇹        implicit inputs; swap order
 Ř       Řangify
  Ʃ      Ʃum; implicit print

```

If the input can be taken in the opposite order (B, then A), then a two-byte solution works:

# Pyt, 2 bytes

```
ŘƩ

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `S`, 1 byte

```
I

```

Attempt This Online!

Built-in for `I`nclusive range. The flag `S`ums the resulting list.
> 0 votes

# Answer
# sed, 54 bytes

```
s/>$/!>/
:a
s/<(!*)><((\1)!+)>/\1<\1!><\2>/
ta
s/<.*//

```

Each number is inputed as unary exclamation marks surrounded by `<>` signs. Output is just exclamation marks. For example: `<!><!!!>` gives `!!!!!!`.

Try it online!
> 0 votes

# Answer
# J-uby, 8 bytes

```
:!~|:sum

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, math, arithmetic
---


title: Write a program with the smallest width

text:
# Question
Title: Write a program with the smallest width
Print or return the following text:

```
Hello world! The quick brown fox jumps over a lazy dog.

```

However, your submission will not be scored in bytes. Instead, primarily it will be scored by the width in pixels of the program when written in Arial in a 12pt font. In particular, the score is:

$$ (\text{visual width in px}) + \frac{1}{1000}(\text{length in characters})$$

Since there might be slight differences based on platform, OS etc the following program will be used to judge your score:

Try it online!

### Rules

* Standard I/O rules apply.
* A single trailing newline is optionally permitted in the output. No other variation is permitted.
* Lowest score as calculated by the above program wins.
* Note that the measure of visual width used ignores newlines. As far as I can tell, you can never reduce the score of your program by adding characters.

# Answer
# Zalgo, score ~~5.221~~ 0.222

```
̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̐̈̄̐̅̆̐̌̆̐̌̆̐̏̆̐̀̂̐̇̇̐̏̆̐̂̇̐̌̆̐̄̆̐́̂̐̀̂̐̄̅̐̈̆̐̅̆̐̀̂̐́̇̐̅̇̐̉̆̐̃̆̐̋̆̐̀̂̐̂̆̐̂̇̐̏̆̐̇̇̐̎̆̐̀̂̐̆̆̐̏̆̐̈̇̐̀̂̐̊̆̐̅̇̐̍̆̐̀̇̐̃̇̐̀̂̐̏̆̐̆̇̐̅̆̐̂̇̐̀̂̐́̆̐̀̂̐̌̆̐́̆̐̊̇̐̉̇̐̀̂̐̄̆̐̏̆̐̇̆̐̎̂

```

Score this online!

I think I found the ~~perfect~~ **uberperfect** language! Tested with the official interpreter locally. Now also uses dingledooper's observation that zalgo surrounded by two `\u200b`s has width zero. Luckily (and surprisingly) `\u200b` is not considered as a whitespace in the interpreter (which uses Rust's `char.is_whitespace`).

Script to generate the source:

```
s = 'Hello world! The quick brown fox jumps over a lazy dog.'
ans = '\u200b'
ans += '\u031d' * len(s)
for c in s:
    d = ord(c)
    ans += '\u0310' + chr(0x300 + d % 16) + chr(0x300 + d // 16)
print(ans + '\u200b', end='')

```

Try it online!
> 31 votes

# Answer
# Python, 125.833 score

```
ᵉᵛªˡ(ᵇʸᵗᵉſ(ᵐªᵖ(ˡᵉⁿ,''.ſᵖˡᵢᵗ(''))))

```

Attempt This Online! *or* Score this online!

### Explanation

Through some experimentation, I found that `\u200a` (zero width space) takes up **zero** pixels. In addition, as kindly pointed out by Mukundan314, `\u200c` seems to use up zero pixels as well, though only when surrounded by `\u200a`. Using this fact, I created an algorithm to encode any string using only the characters `\u200c` and `\u200a`. The algorithm works by encoding each character as a string of `\u200c`s whose size is the value of its unicode codepoint. Then, they are joined together by `\u200a`.

Then, decoding it is simply a matter of splitting the string by the `\u200c` delimiter, mapping each element to its length, and converting it back into a string using the `bytes` builtin:

```
bytes(map(len,'...'.split('\u200c')))

```

In the implementation, the strange-looking unicode characters are converted to ASCII due to Python's implicit NFKC normalization of identifiers, which help slightly shorten the pixel width.

# Python, 139.097 score

*-0.002 score thanks to @Neil, who noticed that the `\u200b`s are apparently unnecessary here.*

```
ᵉᵛªˡ(ᵇʸᵗᵉſ(ºʳᵈ(ˡ)%126for ˡ in'ֲًٌٍٍِّّ֑᷿͈ۘۚ︠̔ۘ̔̔ۛٓ̔̕ﱢٍَْ᷿ۘ̔ͬ̔ۛۙ̔᷾ۘ̔ﱡ̔ﱡٌُ֑۠۟̔︡'))
```

Attempt This Online!

An alternative solution, which although longer, may port better to other languages. The idea here is that any string of accent characters embedded between two `\u200b`s has a pixel width of zero.
> 30 votes

# Answer
# Charcoal, score ~~49.089~~ ~~27.235~~ 27.107

```
⍘⍘̔̆́̐̐̑̊̓̇̂̐̇̋̒́̒̎̏̌́̄̐́̉̌̇̀̍̌̌̓̒̊̋̎́̄̎̅̍̃̂̒̃̂̉̏̑̈̋̄̎̋̂̂̃̋̋̍̎̀̈̍̀̆̇̐́̐̒́̑̄̑̎̒̌̎̑̐̔̄¦̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔γ

```

Try it online! No verbose version because the deverbosifier extraneously quotes the strings, which is longer than using the `¦` separator. Explanation: Converts a string from base `\u0300-\u0314` and then into base  `-~` (printable ASCII).

```
  ̔̆́̐̐̑̊̓̇̂̐̇̋̒́̒̎̏̌́̄̐́̉̌̇̀̍̌̌̓̒̊̋̎́̄̎̅̍̃̂̒̃̂̉̏̑̈̋̄̎̋̂̂̃̋̋̍̎̀̈̍̀̆̇̐́̐̒́̑̄̑̎̒̌̎̑̐̔̄      Literal string of \u0300-\u0314 characters
 ⍘      Convert from base
   ̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔     Literal string `\u0300-\u0314`
⍘       Convert to base
   γ    Predefined variable printable ASCII
        Implicitly print

```
> 7 votes

# Answer
# K (ngn/k), score 64.584

```
`0:`c$#'""\""

```

Try it online! or Score this online!

A port of dingledooper's answer to K. Uses `\u200b` as the "word" character and `\u200c` as the separator. The only difference is that "length" `#` counts each "space" character as 3 bytes, so I had to do a little calculation so that `(word length in characters) * 3 % 256 == output character`.
> 5 votes

# Answer
# Vyxal `s`, Score 41.09

```
``\/vLC

```

Try it Online!

Port of dingledooper's answer.
> 2 votes

# Answer
# Brachylog, score: 494.078 (78 bytes)

```
"He
llo
 wo
rld
! T
he
qui
ck
bro
wn
fox
 ju
mps
 ov
er
a l
azy
 do
g.
"ṇc

```

Try it online!

Not as competitive as the rest, but the program contains the expected string with no specific encoding.

### Explanation

`"ṇc` ends a string, splits it on linebreaks into a list of strings, and then concatenates it back into a single string with no linebreaks.

We then split the string into chunks of at most 3 chars with linebreaks, as Brachylog supports inline multi-line strings.
> 2 votes

# Answer
# Mathematica, score 261.096

```
FromCharacterCode[ToCharacterCode@"̴̨͈͕͉͎͕͍͓͖͚͙͇͌͌̀͗͒͌̈́́̀̀͑̓͋̀͂͒͗̀͆̀͊͐̀͒̀́̀͌́̀̈́̎͘ͅͅͅ"-736]

```

View it on Wolfram Cloud!

Score it online!
> 1 votes

# Answer
## Pascal, 495.092

```
program i(output);begin write('Hello world! The quick brown fox jumps over a lazy dog.')end.

```
> 1 votes

# Answer
# 05AB1E, score 40.062

```
’̴̨͈͕͉͎͕͍͓͖͚͙͇͌͌̀͗͒͌̈́́̀̀͑̓͋̀͂͒͗̀͆̀͊͐̀͒̀́̀͌́̀̈́̎͘ͅͅͅ’ÇŽ2ã-

```

Try it online! Outputs as a list of byte values.
> 1 votes

# Answer
# Japt, score ~~30.062~~ 29.061

```
"̴̨͈͕͉͎͕͍͓͖͚͙͇͌͌̀͗͒͌̈́́̀̀͑̓͋̀͂͒͗̀͆̀͊͐̀͒̀́̀͌́̀̈́̎͘ͅͅͅ"c-#ˠ

```

Test it
> 1 votes

# Answer
# Pyth, score 58.092

```
smCldc""\

```

Try it here!

Score it online!

Near literal translation of dingledooper's Python answer.
> 0 votes

---
Tags: code-challenge, kolmogorov-complexity, hello-world
---


title: Square pyramidal numbers

text:
# Question
Title: Square pyramidal numbers
A000330 - OEIS

# Task

Your task is simple, generate a sequence that, given index `i`, the value on that position is the sum of squares from `0` upto `i` where `i >= 0`.

# Example:

```
Input: 0
Output: 0           (0^2)

Input: 4
Output: 30          (0^2 + 1^2 + 2^2 + 3^2 + 4^2)

Input: 5
Output: 55          (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2)

```

# Specification:

* You may take no input and output the sequence indefinitely;
* You may take input `N` and output the `Nth` element of the sequence;
* You may take input `N` and output the first `N` elements of the sequence.

# Answer
> 4 votes
# Jelly, 3 bytes

```
R²S

```

Try it online!

FGITW

# Explanation

```
R²S  Main Link
R    Generate Range
 ²   Square (each term)
  S  Sum

```

# Answer
> 22 votes
# Python 2, 22 bytes

```
lambda n:n*~n*~(n*2)/6

```

Try it online!

This uses the closed-form formula **n * (n+1) * (2\*n+1) / 6**. The code performs the following operations:

* Multiplies **n** by (`n*`):

+ The bitwise complement of **n** (`~n`), which essentially means **-1-n**.
    + And by the bitwise complement of **2n** (`*~(n*2)`), which means **-1-2n**.
* Divides by **6** (`/6`).

# Python 2, 27 bytes

```
f=lambda n:n and f(n-1)+n*n

```

Try it online!

Saved 1 byte thanks to Rod and 1 thanks to G B.

# Answer
> 14 votes
# MATL, 3 bytes

```
:Us

```

... or them?

**Try it online!**

### Explanation

```
:Us
:    % Implicit input n. Push range [1 2 ... n]
 U   % Square, element-wise
  s  % Sum of array. Implicit display

```

# Answer
> 14 votes
# JavaScript (ES6), 16 bytes

```
n=>n*(n+++n)*n/6

```

### Demo

```
let f =

n=>n*(n+++n)*n/6

for(n = 0; n < 10; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```

### How?

The expression `n+++n` is parsed as `n++ + n` (1). Not that it really matters because `n + ++n` would also work in this case.

Therefore:

```
n*(n+++n)*n/6 =
n * (n + (n + 1)) * (n + 1) / 6 =
n * (2 * n + 1) * (n + 1) / 6

```

which evaluates to **sum(k=0...n)(k²)**.

---

*(1) This can be verified by doing `n='2';console.log(n+++n)` which gives the integer `5`, whereas `n + ++n` would give the string `'23'`.*

# Answer
> 6 votes
# 05AB1E, 3 bytes

```
ÝnO

```

Try it online!

**Explanation**

```
  O    # sum of
 n     # squares of
Ý      # range [0 ... input]

```

# Answer
> 6 votes
# Brain-Flak, 36 bytes

```
({<(({}[()])())>{({})({}[()])}{}}{})

```

Try it online!

```
# Main algorithm
(                                  )  # Push the sum of:
                {({})({}[()])}{}      #   The square of:
 {                              }     #     0 to i

# Stuff for the loop
  <(({}[()])())>                      # Push i-1, i without counting it in the sum
                                 {}   # Pop the counter (0)

```

# Answer
> 6 votes
# Brain-Flak, 34 bytes

```
({(({}[()])()){({}[()])({})}{}}{})

```

Try it online!

# How does it work?

Initially I had the same idea as Riley1 but it felt wrong to use a zeroer. I then realized that

```
{({}[()])({})}{}

```

Calculates n2 \- n.

Why? Well we know

```
{({})({}[()])}{}

```

Calculates n2 and loops n times. That means if we switch the order of the two pushes we go from increasing the sum by n + (n-1) each time to increasing the sum by (n-1) + (n-1) each time. This will decrease the result by one per loop, thus making our result n2 \- n. At the top level this -n cancels with the n generated by the push that we were zeroing alleviating the need for a zeroer and saving us two bytes.

# Brain-Flak, 36 bytes

```
({({})(({}[()])){({})({}[()])}{}}{})

```

Try it online!

Here is another solution, its not as golfy but it's pretty strange so I thought I would leave it as a challenge to figure out how it works.

If you are not into Brain-Flak but you still want the challenge here it is as a summation.

---

1: I came up with my solution before I looked at the answers here. So no plagiarism here.

# Answer
> 4 votes
# Husk, 3 bytes

```
ṁ□ḣ

```

Try it online!

# Answer
> 4 votes
## Hexagony, 23 bytes

```
?'+)=:!@/*"*'6/{=+'+}/{

```

Try it online!

### Explanation

Unfolded:

```
   ? ' + )
  = : ! @ /
 * " * ' 6 /
{ = + ' + } /
 { . . . . .
  . . . . .
   . . . .

```

This is really just a linear program with the `/` used for some redirection. The linear code is:

```
?'+){=+'+}*"*'6{=:!@

```

Which computes **n (n+1) (2n+1) / 6**. It uses the following memory edges:

Where the memory point (MP) starts on the edge labelled **n**, pointing north.

```
?   Read input into edge labelled 'n'.
'   Move MP backwards onto edge labelled 'n+1'.
+   Copy 'n' into 'n+1'.
)   Increment the value (so that it actually stores the value n+1).
{=  Move MP forwards onto edge labelled 'temp' and turn around to face
    edges 'n' and 'n+1'.
+   Add 'n' and 'n+1' into edge 'temp', so that it stores the value 2n+1.
'   Move MP backwards onto edge labelled '2n+1'.
+   Copy the value 2n+1 into this edge.
}   Move MP forwards onto 'temp' again.
*   Multiply 'n' and 'n+1' into edge 'temp', so that it stores the value
    n(n+1).
"   Move MP backwards onto edge labelled 'product'.
*   Multiply 'temp' and '2n+1' into edge 'product', so that it stores the
    value n(n+1)(2n+1).
'   Move MP backwards onto edge labelled '6'.
6   Store an actual 6 there.
{=  Move MP forwards onto edge labelled 'result' and turn around, so that
    the MP faces edges 'product' and '6'.
:   Divide 'product' by '6' into 'result', so that it stores the value
    n(n+1)(2n+1)/6, i.e. the actual result.
!   Print the result.
@   Terminate the program.

```

In theory it might be possible to fit this program into side-length 3, because the `/` aren't needed for the computation, the `:` can be reused to terminate the program, and some of the `'"=+*{` might be reusable as well, bringing the number of required commands below 19 (the maximum for side-length 3). I doubt it's possible to find such a solution by hand though, if one exists at all.

# Answer
> 3 votes
# Ohm v2, 3 bytes

```
#²Σ

```

Try it online!

**Explanation**

```
#    Range
 ²   Square
  Σ  Sum

```

# Answer
> 3 votes
# Japt, 3 bytes

```
ô²x

```

Try it here.

-1 thanks to Shaggy.

Explanation:

```
ò²x
ô²  Map square on [0..input]
  x Sum

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 14 bytes

```
Tr[Range@#^2]&

```

Try it online!

# Answer
> 2 votes
# Brain-Flak, 46 bytes

```
{(({})[()])}{}{({({})({}[()])}{}<>)<>}<>({{}})

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog), ~~7~~ 5 bytes

*2 bytes saved thanks to @Mego*

```
+.×⍨⍳

```

Try it online!

**How?**

\- range

`+.×` \- dot product

\- with itself

# Answer
> 2 votes
# CJam, 10 bytes

```
ri),{_*+}*

```

**Try it online!**

```
ri            e# Input integer n
  )           e# Add 1
   ,          e# Range [0 1 ... n]
    {   }*    e# Fold (reduce)
     _        e# Duplicate
      *       e# Multiply
       +      e# Add

```

# Answer
> 2 votes
# Julia, ~~16~~ 14 bytes

*2 bytes saved thanks to @MartinEnder*

```
!n=(x=1:n)⋅x

```

Try it online!

**How?**

`(x=1:n)` creates a range of `1` to `n` and assign to `x`,  dot product with `x`.

# Answer
> 2 votes
# Brachylog, 5 bytes

```
⟦^₂ᵐ+

```

Try it online!

### Explanation

```
⟦        Range
 ^₂ᵐ     Map square
    +    Sum

```

# Answer
> 2 votes
# Actually, 3 bytes

```
R;*

```

Try it online!

Takes `N` as input, and outputs the `N`th element in the sequence.

Explanation:

```
R;*
R    range(1, N+1) ([1, 2, ..., N])
 ;*  dot product with self

```

# Answer
> 2 votes
# Befunge, 16 bytes

```
&::2*1+*\1+*6/.@

```

Using the closed-form formula **n\*(n+1)\*(2n+1)/6**.

Try it online!

# Befunge, 38 bytes

```
v>::*\1-:v0+_$.@
&^ <     _\:^
>:#^_.@

```

Using a loop.

Try it online!

# Answer
> 2 votes
## R, 17 bytes

```
sum((0:scan())^2)

```

Pretty straightforward, it takes advantage from the fact that `^` (exponentiation) is vectorized in **R**.

# Answer
> 2 votes
## CJam, 9 bytes

```
ri),_.*:+

```

Try it online!

### Explanation

```
ri        e# Read input and convert to integer N.
  ),      e# Get range [0 1 2 ... N].
    _     e# Duplicate.
     .*   e# Pairwise products, giving [0 1 4 ... N^2].
       :+ e# Sum.

```

Alternatively:

```
ri),2f#:+

```

This squares each element by mapping `2#` instead of using pairwise products. And just for fun another alternative which gets inaccurate for large inputs because it uses floating-point arithmetic:

```
ri),:mh2#

```

# Answer
> 2 votes
# Cubix, 15 bytes

```
Iu):^\+*p*6u@O,

```

Try it online!

My code is a bit sad `):`

Computes `n*(n+1)*(2n+1)/6`

```
    I u
    ) :
^ \ + * p * 6 u
@ O , . . . . .
    . .
    . .

```

```
^Iu : read in input, u-turn
    : stack  n
:)\ : dup, increment, go right..oh, hey, it cheered up!
    : stack: n, n+1
+   : sum
    : stack: n, n+1, 2*n+1
*   : multiply
    : stack: n, n+1, 2*n+1, (n+1)*(2*n+1)
p   : move bottom of stack to top
    : stack: n+1, 2*n+1, (n+1)*(2*n+1), n
*   : multiply
6   : push 6
u   : right u-turn
,   : divide
O   : output
@   : terminate

```

# Answer
> 2 votes
# \>\<\>, ~~15~~ ~~13~~ 11 bytes

Saved 2 bytes thanks to *Not a tree*

```
0:n:l1-:*+!

```

Try it online!

Outputs the sequence indefinitely.

# Answer
> 2 votes
## Labyrinth, 11 bytes

```
:!\
+ :
*:#

```

Try it online!

Prints the sequence indefinitely.

### Explanation

The instruction pointer just keeps running around the square of code over and over:

```
:!\    Duplicate the last result (initially zero), print it and a linefeed.
:      Duplicate the result again, which increases the stack depth.
#      Push the stack depth (used as a counter variable).
:*     Square it.
+      Add it to the running total.

```

# Answer
> 2 votes
# Pyth, 7 5 bytes thanks to Steven H

```
s^R2h

```

Explanation:

```
s^R2h       Full program - inputs from stdin and outputs to stdout
s           output the sum of
    h       range(input), with
 ^R2         each element squared

```

---

My first solution

```
sm*ddUh

```

Try it online!

Explanation:

```
sm*ddUh    Full program - inputs from stdin and outputs to stdout
s          sum of
 m   Uh    each d in range(input)
  *dd      squared

```

# Answer
> 2 votes
## Haskell, 20 bytes

```
f 0=0
f n=n*n+f(n-1)

```

Try it online!

# Answer
> 2 votes
# , ~~10~~ 9 bytes

```
4%~3!2*>:

```

Try it online!

*Saved 1 byte using an explicit formula, thanks to miles!*

---

## J, 10 bytes

```
1#.]*:@-i.

```

J has a range function, but this gives us number from `0` to `N-1`. To remedy this, we can just take the argument and subtract the range from it, giving us a range from `N` to `1`. This is done with `] -i.`. The rest of the code simply square this list argument (`*:@`) and then sums it (`1#.`).

## Other contenders

**11 bytes**: `1#.*:@i.@>:`

**13 bytes**: `1#.[:,@:*/~i.`

# Answer
> 2 votes
# Excel, 19 bytes

```
=A1^3/3+A1^2/2+A1/6

```

# Answer
> 2 votes
# Thunno 2 `S`, 2 bytes

Attempt This Online!

#### Explanation

```
R²  # Implicit input
R   # Range of input
 ²  # Square each
    # Sum the list
    # Implicit output

```

# Answer
> 2 votes
# Nekomata, 3 bytes

```
R:∙

```

Attempt This Online!

```
R:∙
R     Range
 :    Duplicate
  ∙   Dot product

```

Because there isn't a square built-in yet.

# Answer
> 1 votes
# Oasis, 4 bytes

```
nk+0

```

Try it online!

**Explanation**

```
   0      # a(0) = 0
nk+       # a(n) = a(n-1)+n^2

```

# Answer
> 1 votes
# Neim, 3 bytes

This could've been a challenge to show off Neim's polygonal number builtins, but apparently not.

Try it online!

# Answer
> 1 votes
# Gaia, 3 bytes

```
s¦Σ

```

Try it online!

# Answer
> 1 votes
# Ruby, 18 bytes

```
->n{n*~n*~(n+n)/6}

```

Using the sama formula as everybody else, saved 1 byte with a double negative multiplication.

Try it online!

# Answer
> 1 votes
# Perl 5, ~~24~~, 21 bytes

Thanks to Dom, solutions with 21 bytes

```
$\+=$_--**2while$_}{

```

or

```
map$\+=$_**2,1..$_}{

```

or

```
$\+=$_**2for 1..$_}{

```

previous were 21 + 1 `-p` flag, 3 bytes saved thanks to Xcali

```
$_*=($_+1)*(2*$_+1)/6

```

and 23 +1

```
$_=$_*($_+1)*(2*$_+1)/6

```

or

```
$_=$_**3/3+$_**2/2+$_/6

```

# Answer
> 1 votes
# awk, 25 bytes

```
{print$1^3/3+$1^2/2+$1/6}

```

# Answer
> 1 votes
# dc, ~~15~~ 12 bytes

```
d1+dd+1-**6/

```

This is simply the factorised Faulhaber polynomial: n(n+1)(2n+1)/6, except that the (2n+1) term is calculated as 2(n+1)-1.

# Answer
> 1 votes
# Funky, ~~33~~ ~~24~~ 19 bytes

*-9 bytes thanks to Dennis*

*-5 bytes thanks to ASCII-only and bugfixes.*

```
f=n=>n?f(n-1)+n*n:0

```

Try it online!

# Answer
> 1 votes
# Befunge, 28 bytes

```
&00pg#v_.@
-1:g00<^g00+*:p00

```

Works for inputs in the range \[0, 128). Due to befunge being entirely stack-based, and yet having limited stack manipulation operations available, the only way to work with three values (sum, partial sum, and counter) is to store a value temporarily by modifying the program itself using the `p` instruction. Since `p` assigns a value as ASCII, the stored value wraps around at 128, storing a negative value instead of a positive value.

Try it online!

# Befunge, 30 bytes

```
& >::*\:v
$<^-1_v#<@.
_^#:\+<\

```

Works for pretty much any input.

Try it online!

# Answer
> 1 votes
# Python, ~~38~~ 33 bytes

-5 bytes thanks to Martin Ender

```
g=lambda x:x*x+g(x-1) if x else 0
```

Haven't seen any solution with recursion yet, so I thought I'd post this one. It may not be really competitive, but this is my first time posting.

**Edit:** It would've been -11 bytes thanks to Martin Ender, but I would've ended up with the same answer as Mr. Xcoder's

# Answer
> 1 votes
# Jelly, 3 bytes

```
Rḋ`

```

Try it online!

# Answer
> 1 votes
# Flurry, 30 bytes

```
{}{({})[<><<>()>]<[][]>}[<>()]

```

### Run example

```
$ ./flurry -nin -c "{}{({})[<><<>()>]<[][]>}[<>()]" 0
0
$ ./flurry -nin -c "{}{({})[<><<>()>]<[][]>}[<>()]" 1
1
$ ./flurry -nin -c "{}{({})[<><<>()>]<[][]>}[<>()]" 3
14
$ ./flurry -nin -c "{}{({})[<><<>()>]<[][]>}[<>()]" 6
91

```

The computation is done via the stack, but the final result is outputted from the return value.

Given that we can keep track of iteration indexes using the stack height and multiplication is cheap in Flurry, there's really no "clever" alternative that can lead to shorter code.

```
{}{...}[<>()]  Repeat the lambda n times with the start value of zero
                 (implicit) push argument x to the stack
  ({})           Pop and re-push x; return x
  [<><<>()>]     succ
  <[][]>         (height ∘ height)
                 In effect, push x and return x + height^2

```

# Answer
> 1 votes
# Vyxal, 3 bytes

```
ɾ²∑

```

Try it Online!

### Explained

```
ɾ²∑
ɾ   # range 1 inclusive [1...n]
 ²  # square
  ∑ # sum

```

# Answer
> 1 votes
# Pyt, 3 bytes

```
ř²Ʃ

```

Try it online!

```
ř²Ʃ
       implicit input
ř      creates array of 1 to n
 ²     squares each element
  Ʃ    sums the list
       implicit print

```

# Answer
> 1 votes
# Arturo, 19 bytes

```
$=>[∑map&=>[&^2]]

```

Try it!

# Answer
> 1 votes
# Raku, 16 bytes

```
[\+] {$++²}...*

```

Try it online!

This is an expression for the lazy infinite sequence of numbers.

* `{ $++² } ... *` is the infinite sequence of square numbers. `$` is an anonymous state variable whose postincremented value is squared to obtain each new element.
* `[\+]` is the sequence of partial sums of that sequence.

# Answer
> 0 votes
# Proton, 16 bytes

```
x=>x*(x+++x)*x/6

```

Try it online!

Straightforward Solution: `range+map(x=>x**2)+sum`

-2 bytes thanks to Arnauld('s answer)

# Answer
> 0 votes
# QBIC, 13 bytes

```
[:|p=p+a^2]?p

```

## Explanation

```
[:|    FOR a = 1 to <input from cmd line>
p=p+   increment p by
a^2    a squared
]      NEXT
?p     PRINT p

```

# Answer
> 0 votes
# Java 8, ~~78~~ ~~57~~ ~~35~~ 16 bytes

@Arnauld port

```
i->i*(i+++i)*i/6

```

# Answer
> 0 votes
# Pyke, 4 bytes

```
hLXs

```

Try it here!

**or...**

```
SMXs

```

# Answer
> 0 votes
# , 39 bytes

```
3.7006110180020100000030301100001195034

```

Try it online!

**How?**

```
3.
7 00        grid[0] = input()
6 11 01     grid[11] = 1
8 00        while grid[0] != 0:
2 01 00 00     grid[1] = grid[0] * grid[0]
0 03 03 01     grid[3] = grid[3] + grid[1]
1 00 00 11     grid[0] = grid[0] - grid[11]
9
5 03        print(grid[3])
4

```

# Answer
> 0 votes
# Octave, 14 bytes

```
@(k)(a=0:k)*a'

```

Try it online!

\*Dot product.

Or

```
@(k)sumsq(0:k)

```

Try it online!

# Answer
> 0 votes
# Haskell, 21 bytes

```
f n=n*(n+1)*(2*n+1)/6

```

Try it online!

Boring, straightforward implementation of the closed-form formula on the OEIS page. Expanding into polynomial form doesn't save any bytes: `f n=(2*n^3+3*n^2+n)/6`.

# Answer
> 0 votes
# Tcl, 36 bytes

```
proc S n {expr $n*($n+1)*(2*$n+1)/6}

```

Try it online!

# Answer
> 0 votes
# ARBLE, ~~14~~ 13 bytes

*-1 bytes thanks to Mr. Xcoder*

```
n*~n*~(n+n)/6

```

Try it online!

# Answer
> 0 votes
## Alice, ~~17~~ 12 bytes

```
./ O \d2E+.

```

Try it online!

Prints the sequence indefinitely.

The trailing linefeed is significant.

### Explanation

```
.   Duplicate the current total. Initially this pushes two zeros onto the
    previously empty stack.
/   Switch to Ordinal.
O   Print the current total with a trailing linefeed.
\   Switch back to Cardinal.
d   Push the stack depth, which acts as a counter variable.
2E  Square it.
+   Add it to the current total.
.   Duplicate it to increment the stack depth for the next iteration.

```

# Answer
> 0 votes
## Retina, 20 bytes

```
.+
$*
M!&`.+
1
$%_
1

```

Try it online!

### Explanation

```
.+
$*

```

Convert input to unary.

```
M!&`.+

```

Get all overlapping matches of `.+` which turns the input into a range of unary numbers from **1** to **n**.

```
1
$%_

```

Replace each `1` with the entire line its on, squaring the unary value on each line.

```
1

```

Count the number of `1`s, summing all lines and converting them back to decimal.

# Answer
> 0 votes
# Pari/GP, 16 bytes

```
n->(v=[0..n])*v~

```

Try it online!

# Answer
> 0 votes
# cQuents 0, 3 bytes

```
;$$

```

Try it online!

Take that, Oasis.

## Explanation

```
;     Mode: Sum - given n, output the sum of the sequence up to n
 $$   Each term in the sequence equals the index * the index

```

# Answer
> 0 votes
# Recursiva, 8 bytes

```
smBa'Sa'

```

Try it online!

# Answer
> 0 votes
# Bash, ~~48~~ 30 bytes

```
echo "$1*($1+1)*(2*$1+1)/6"|bc

```

Try it online!

# Answer
> 0 votes
# Pyth, 10 bytes

```
VhQ=+Z^N2Z

```

Outputs the first N elements of the sequence.

Try it online!

---

How?

```
VhQ=+Z^N2Z              Full program

VhQ                     Loop until Q + 1 is reached
   =+Z                  Assign and increment Z by ...
      ^N2               ... N squared
         Z              Implicity prints Z

```

---

11 byte alternative.

```
VhQ aY^N2sY

```

Try it online!

# Answer
> 0 votes
# Pushy, 6 bytes

```
R2KeS#

```

**Try it online!**

### Explanation

```
R     Push integers from 1 to implicit n, where n is implicit input
2     Push 2
K     Next command will use the entire stack
e     Pop 2. Raise each of the remaing stack entries to that
S     Sum the entire stack
#     Print as integer

```

# Answer
> 0 votes
# Jq 1.5, 20 bytes

```
[range(.+1)|.*.]|add

```

Input is `N`. Output is `N`'th element of sequence. Expanded:

```
[
    range(.+1)            # generate series 0, 1, 2, 3, ... N
  | .*.                   # square each term
]                         # collect into an array
| add                     # compute the sum

```

Try it online!

# Answer
> 0 votes
# K (oK), 9 bytes

**Solution:**

```
+/x*x:!1+

```

Try it online!

**Examples:**

```
> +/x*x:!1+4
30
> +/x*x:!1+5
55

```

**Explanation:**

Evaluated right-to-left:

```
+/x*x:!1+ / solution
       1+ / add 1 to input, 1+4 => 5
      !   / til, !5 => 0 1 2 3 4
    x:    / save as variable x
  x*      / vectorised multiplication, x*x, 0 1 2 3 4*0 1 2 3 4 => 0 1 3 9 16
+/        / addition over (sum), +/0 1 3 9 16 => 30

```

# Answer
> 0 votes
# C#(.NET Core), 20 bytes

```
a=>a*(a+1)*(2*a+1)/6

```

Try it online!

# Answer
> 0 votes
# , 16 bytes

```
(n=0:scan())%*%n

```

Try it online!

# Answer
> 0 votes
# TacO, 10 bytes

```
@i i
+%+*i

```

Try it online!

# Answer
> 0 votes
# Threead, 40 bytes

```
I[     -]_
   _^>1
  _2 _r

[<

 lo
 ]
+

```

Try it online!

## De-sliced

This is actually 4 bytes larger, due to whitespace.

```
I[     -]_   lo
   _^>1   [< ]
  _2 _r     +

```

## Process.

1. Read an integer into the first value
2. While the first value is non-zero.
    1. Blank the third value, push 2 onto it.
    2. Blank the second value, then calculate the first value to the power of the third, (i^2)
    3. Move the second value to the right and place a 1 onto it.
    4. Put the value of the first value onto the third value.
    5. Calculate the third value minus the second value (i-1)
3. Now the second tape contains the squares of all numbers from inp to 1 squared.
4. Blank the first value
5. While the second value is non-zero
    1. Move the second tape to the left.
    2. Add the first value to the second value into the third value.
    3. Move the third value into the first value
6. Now, all the i^2 values are summed together, output the first value.

# Answer
> 0 votes
# ReRegex, 53 bytes

```
#import math
^k([1-9]\d*)/k($1-1)+$1*$1/k0+/0/k#input

```

## Explained

```
#import math                # Import the math library.
^k([1-9]\d*)/k($1-1)+$1*$1/ # Search the buffer for "k" followed by a non-zero number. Replace it with "k<n-1>+n*n"
k0+/0/                      # Replace k0 with just 0
k#input                     # Default the buffer to k<input>

```

Try it online!

# Answer
> 0 votes
## TI-BASIC, 10 bytes

```
sum(seq(X²,X,0,Ans

```

Quite simple. The sum of the sequence of the first `Ans` squares.

# Answer
> 0 votes
# MaybeLater, 36 bytes

```
n=(readn)/1
write(n*(n+1)*(1+n*2)/6)

```

Using the closed form formula.

Try it online!

# Answer
> 0 votes
# Common Lisp, 30 bytes

```
(loop as i to(read)sum(* i i))

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6), 18 bytes

```
f=n=>n&&n*n--+f(n)

```

---

## Try it

```
o.innerText=(
f=n=>n&&n*n--+f(n)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 0 votes
# TI-Basic, 10 bytes

```
sum(seq(OO,O,0,Ans

```

sp00ky

# Answer
> 0 votes
# Milky Way, 10 bytes

```
'L§{:*}G!

```

Try it online!

## Explanation:

```
'          push input to stack
 L         push inclusive range
  ${  }    map over every element ...
    :*     ... duplicate and multiply (square it)
       G   sum of list
        !  output

```

# Answer
> 0 votes
# Add++, 13 bytes

```
D,f,@,RdBcB*s

```

Try it online!

```
D,f,@,   - Create a monadic function called f. Argument n (example: 5)
      R  - Generate range;   STACK = [[1 2 3 4 5]]
      d  - Duplicate;        STACK = [[1 2 3 4 5] [1 2 3 4 5]]
      Bc - Push the columns; STACK = [[1 1] [2 2] [3 3] [4 4] [5 5]]
      B* - Product of each;  STACK = [1 4 9 16 25]
      s  - Push the sum;     STACK = [1 4 9 16 25 55]
         - Implicitly return 55

```

# Answer
> -1 votes
# Postscript, 149 bytes

```
/d {def}def
/a {
0 i l 1 0 l
i 2 ge {/i i 1 sub d a}if
} d
/l {rlineto}d
/m {moveto}d
/b {/j exch d /i j d 0 0 m j a j 0 lineto closepath fill}d
5 b

```

---
Tags: code-golf, number, sequence, arithmetic
---


# Question
Title: compute number of 1 bits in a binary representation of a number
The goal is to write a program that returns number of 1 bits in a given number.

## Examples

```
5      ->  2
1254   ->  6
56465  ->  8

```

## Winner

The winning submission is the code which runs in the minimum time. You can assume that normal int value in your language can handle any number (no matter how large) and computes all the valid operators defined for integer in O(1).

If two pieces of code run in the same time the winner is the one implemented in fewer bytes.

Please provide some explanation how your code is computing the result.

# Answer
> 10 votes
## C/C++<br>

```
int popcnt(int n)
{
    return __builtin_popcount(n);
}

```

For some CPUs `__builtin_popcount` compiles to a single instruction (e.g. `POPCNT` on x86).

Note: requires gcc or gcc-compatible compiler (e.g. ICC).

# Answer
> 3 votes
Using an 8-bit lookup table in the python shell

```
>>> tab=[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8]
>>> N=123456789
>>> tab[N>>24]+tab[N>>16&255]+tab[N>>8&255]+tab[N&255]
16

```

# Answer
> 3 votes
### Haskell, 9 (+16)

There was a `popCount` routine added to the `Data.Bits` module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).

```
import Data.Bits
popCount

```

There is a good arbitrary precision popcount function in the GNU Multiple Precision Arithmetic Library (GMP), which GHC uses by default, but most other serious languages offer bindings to :

### Python, 16 (+12)

```
import gmpy;
gmpy.popcount(...);

```

### Perl, 11 (+22)

```
use GMP::Mpz qw(:all);
popcount(...);

```

# Answer
> 2 votes
fastest for 32 bit numbers:

```
int bitcount(int i){
    i=i&0x55555555 + (i>>1)&0x55555555;
    i=i&0x33333333 + (i>>2)&0x33333333;
    i=i&0x0f0f0f0f + (i>>4)&0x0f0f0f0f;
    i=i&0x00ff00ff + (i>>8)&0x00ff00ff;
    return i&0x0000ffff + (i>>16)&0x0000ffff;
}

```

for 64 bits:

```
int bitcount(long i){
    i=i&0x5555555555555555 + (i>>1)&0x5555555555555555;
    i=i&0x3333333333333333 + (i>>2)&0x3333333333333333;
    i=i&0x0f0f0f0f0f0f0f0f + (i>>4)&0x0f0f0f0f0f0f0f0f;
    i=i&0x00ff00ff00ff00ff + (i>>8)&0x00ff00ff00ff00ff;
    i=i&0x0000ffff0000ffff + (i>>16)&0x0000ffff0000ffff;
    return i&0x00000000ffffffff + (i>>32)&0x00000000ffffffff;
}

```

these are all for C-based languages that define the binary operators (C, C++, C#, D, java, ...) (barring the `int` `long` type, translate as needed)

for arbitrary bit sizes:

```
int bitcount(BigInt i){
    int c=0;
    BigInt _2_pow_64 = BigInt(2).pow(64);
    while(i>0){
       long rem = i.mod(_2_pow_64);//or AND with 0xffffffffffffffff
       c+=bitcount(rem);//as defined above
       i=i.div(_2_pow_64);//or rshift with 64
    }
    return c;
}

```

BigInt being the class for integers of arbitrary size, and the `.div`, `.pow`, `.mod` being the 'divide by', 'to the power of' and 'remainder of' functions reps.

# Answer
> 2 votes
### scala:

```
@tailrec
def bits (i: Long, sofar: Int): Int = if (i==0) sofar else bits (i >> 1, (1 & i).toInt + sofar)

```

computes on a 2Ghz single core for about 1.500.000 64bit Long values the number of bits set. A straight forward recursive method, comparing the last bit, and shifting the number towards zero. The `@tailrec` is just a hint to the compiler to warn me, if it can't optimize the tail recursive call - it is not necessary, for the optimization to take place.

It's about 10times faster than the simplest method, using the library function:

```
def f(n:Long)=n.toBinaryString.count(_=='1')

```

Translating them to c++ might not lead to similar results.

# Answer
> 1 votes
Here is rachet freak's submission (the 32-bit version) converted to Scala (thanks RF!):

```
def num1Bits(x: Int) = {
  var i = x
  i = (i & 0x55555555) + ((i>> 1) & 0x55555555)
  i = (i & 0x33333333) + ((i>> 2) & 0x33333333)
  i = (i & 0x0f0f0f0f) + ((i>> 4) & 0x0f0f0f0f)
  i = (i & 0x00ff00ff) + ((i>> 8) & 0x00ff00ff)
      (i & 0x0000ffff) + ((i>>16) & 0x0000ffff)
}

```

# Answer
> 1 votes
### Erlang

```
p(N)->p(N,0).
p(0,S)->S;p(N,S)->p(N div 2, S+N rem 2).

```

The `p` function divides the number with 2, adds the remainder to S, and calls itself with N/2 (tail) recursively.

While it takes log2(N) steps (division and function call) to calculate the result, it works with arbitrary large numbers.

# Answer
> 1 votes
# C, 33 bytes

I just saw the challenge today, but thought of a recursive solution.

```
B(n){return (n&1)+(n?B(n/2):0);};

```

Edited to note that I assumed it was a smallest size challenge. The speed is linear to the number of bits required to contain the number. O(N) = k * Log2(N).

# Answer
> 1 votes
# Python (72 bytes)

```
x=bin(int(input()));n=0
for i in x:
    if i=='1':
        n+=1
print(n)

```

Converts `str`, to `int`, to `bin`, then iterates over the string to count.

# Answer
> 0 votes
# Rust

Rust has its **built-in popcount function**: `(num as u128).count_ones();`

It's also worth noting that \\$\color{blue}{\text{this function operates in constant time}}\\$. That is, regardless of the input value, it always takes the same amount of time to execute. This is because the number of bits in an integer is fixed, so no matter the value, the same number of bits need to be examined.

### u128

Try it online!

```
use std::time::Instant;

fn main() {
    let numbers = vec![5, 1254, 56465];
    let answers = vec![2, 6, 8];

    for (i, &num) in numbers.iter().enumerate() {
        let start = Instant::now();
        let result = (num as u128).count_ones();
        let duration = start.elapsed();

        assert_eq!(result, answers[i], "Failed test for {}", num);
        println!("Number: {}, Ones: {}, Time taken: {:?}", num, result, duration);
    }
}

```

### u256

#### `/src/main.rs`

```
use uint::construct_uint;
use std::time::Instant;

construct_uint! {
    pub struct U256(4);
}

fn count_ones(n: U256) -> u32 {
    n.as_ref().iter().map(|&b| b.count_ones()).sum()
}

fn main() {
    let numbers = vec![
        U256::from(5u64),
        U256::from(1254u64),
        U256::from(56465u64),
        U256::from(18446744073709551615u64),
        U256::from_dec_str("115792089237316195423570985008687907853269984665640564039457584007913129639935").unwrap(),  // 2^256 - 1
    ];

    let answers = vec![2, 6, 8, 64, 256];

    for (i, num) in numbers.iter().enumerate() {
        let start = Instant::now();
        let result = count_ones(num.clone());
        let duration = start.elapsed();

        assert_eq!(result, answers[i], "Failed test for {}", num);
        println!("Number: {}, Ones: {}, Time taken: {:?}", num, result, duration);
    }
}

```

#### `Cargo.toml`

```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
uint = "0.9"
# bitvec = "1.0.1"

```

#### Build and running

```
# win10 environment

$ cargo build
$ target\debug\rust_hello.exe

Number: 5, Ones: 2, Time taken: 600ns
Number: 1254, Ones: 6, Time taken: 700ns
Number: 56465, Ones: 8, Time taken: 400ns
Number: 18446744073709551615, Ones: 64, Time taken: 700ns
Number: 115792089237316195423570985008687907853269984665640564039457584007913129639935, Ones: 256, Time taken: 800ns

```

# Answer
> 0 votes
# Mathematica

**Mathematica has its built-in function `DigitCount`.**

Try it online!

```
popCount[n_Integer] := DigitCount[n, 2, 1];
(ans=popCount[115792089237316195423570985008687907853269984665640564039457584007913129639935])//AbsoluteTiming//Print

```

---
Tags: math, fastest-code, binary
---


# Question
Title: Translate English Characters to the Emoji Flag Alphabet
## Introduction

Emoji use a particular alphabet for their national flags, which allows one to put two symbols together to create the appropriate flag.

Your challenge, is to transform any uppercase letter into the appropriate Flag Identifier.

This may be much harder for languages that do not innately handle Unicode. Each symbol is exactly 4 UTF-8 Bytes.

## The Task

Given an input as one or more letters, output the same, with all letters replaced with their flag combinations.

Winner is the answer with the least *Bytes*, giving the tiebreaker to first answer posted.

## Input / Output

Input and Output may use any standard method. Letters in the input may optionally only support one case, Upper or Lower. Please specify in your answer what case your solution supports.

Your output may, intentionally or otherwise, output flag emoji instead of letter pairs.

## Test Cases

`FR`

`Hello, World!` `, !`

## Rules

* Standard Loopholes Apply
* Standard Input Output allowed
* This is , however, All the Emoji Letters as provided above can be counted for a single byte each, instead of four. Least Bytes wins!

# Answer
# Retina - ~~9~~ 7 bytes

Supports uppercase.

I don't really know retina, so I'm not sure the question mark diamonds show up because of TIO limitations or because I did something wrong, if its the latter, please leave a comment.

```
T`L`-

```

Try it online here.
> 3 votes

# Answer
# Pyth - ~~18~~ 16 bytes

Supports lowercase.

```
XzGsCMrF+BC\26

```

Test Suite.
> 2 votes

# Answer
# 05AB1E, 9 bytes

*Ties Steffan's Vyxal answer for #1.*

```
A""ÇŸç‡

```

Try it online! Supports lowercase only.
> 2 votes

# Answer
# Vyxal, 9 bytes

```
Cʀ»ƛ⁽ṗ»*+

```

Try it Online!
> 2 votes

# Answer
# Lua 5.3, 76 bytes

Lua 5.3 newly has a UTF-8 manipulation library, which is useful in this case.

Lowercase only

```
print(arg[1]:gsub("%l",function(c)return utf8.char(c:byte()+127365)end).."")

```
> 1 votes

# Answer
# Scala, 75 bytes

```
(s:String)=>s.flatMap(c=>if(c.isLetter)Seq(55356,c+56741)else Seq(c))

```

Explanation:

```
(s:String)=>             //define an anonymous function taking a string
  s.flatMap(c=>            //map each char...
    if(c.isLetter)           //if it's a letter
      Seq(55356,c+56741)       //...to a sequence of 55356 and c+56741, this is the target char in UTF16 encoding as a surrogate pair
    else                     //else
      Seq(c)                   //..to a sequence of c
  )                        //and flatten

```

Only works for uppercase. This returns a the output as sequence of integers in UTF16.
> 1 votes

# Answer
# x86-64, 17 bytes

Takes input as UTF-32LE string in `rsi`, and outputs in the same format to a buffer at `rdi`, and code point count in `rcx`. Only works for uppercase letters. This can be linked to C code with the function signature `void f(int *output,int *input,int dummy,int count);`. The dummy variable is just to put the count in the `rcx` register.

`fff10100` is the UTF-32LE encoding for , and so only costs one byte.

```
ad 50 5a 2c 41 2c 19 8d 80 fff10100 0f 47 c2 ab e2 ed c3

```

Or, in assembly:

```
   0:   ad                      lodsd
   1:   50                      push   rax
   2:   5a                      pop    rdx
   3:   2c 41                   sub    al,0x41
   5:   2c 19                   sub    al,0x19
   7:   8d 80 ff f1 01 00       lea    eax,[rax+0x1f1ff]
   d:   0f 47 c2                cmova  eax,edx
  10:   ab                      stosd
  11:   e2 ed                   loop   0
  13:   c3                      ret

```

Uses the string manipulation instruction `lodsd` to load one code point into `eax`, checks if it's a capital letter using two successive subtractions, and adds the appropriate value to convert it to a flag if it is. Otherwise, it uses the conditional move `cmova` to restore its original ascii value. Finally, it uses `stosd` to put a code point in the buffer.
> 1 votes

# Answer
# C (gcc), ~~125~~ 111 bytes

```
main(c,v)char**v;{for(v++;c=**v;putchar(" Ee"[c]+*(*v)++))c=!isalpha(c)-~!islower(c),c%3&&printf(L"\x879ff0");}

```

*-14 bytes thanks to @ceilingcat*

Try it online!
> 1 votes

# Answer
# Jelly, 13 bytes

```
e€ØA×“¢®Ƒ’+OỌ

```

Supports only uppercase letters.

Try it online!

## Explanation

```
e€ØA×“¢®Ƒ’+OỌ  Input: string S
e€             Test if each char in S is an element of
  ØA             the uppercase alphabet 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ×          Multiply by
     “¢®Ƒ’       The codepoints of '¢®Ƒ' as a base 250 integer
                 This forms 127397
          +    Vectorized add with
           O     The codepoints of each char in S
            Ọ  Convert back to char from codepoints
               Return and print implicitly

```
> 0 votes

# Answer
# PHP, 101 Bytes

supports both replace 64 with 96 to support only lowercase. input only ascii characters allowed

```
foreach(str_split($argv[1])as$c)echo($o=ord($c))>64&&$o%32<27?hex2bin("f09f87".dechex($o%32+165)):$c;

```

PHP, 112 Bytes

supports both remove i as modifier in the regex to support only lowercase

```
<?=preg_replace_callback("#[a-z]#i",function($t){return hex2bin("f09f87".dechex(ord($t[0])%32+165));},$argv[1]);

```

first version 205 Bytes

```
<?=preg_replace_callback("#[a-z]#i",function($t){return substr("",(ord($t[0])%32-1)*4,4);},$argv[1]);

```

The version with `mb_substr` is one Byte longer
> 0 votes

# Answer
## JavaScript (ES6), 70 bytes

```
f=
s=>s.replace(/[A-Z]/g,c=>String.fromCodePoint(c.codePointAt()+127397))
;
```

```
<input oninput=o.textContent=f(this.value)><div id=o>
```

Accepts upper case only. Mixed case version for 73 bytes:

```
f=
s=>s.replace(/[A-Z]/gi,c=>String.fromCodePoint(c.codePointAt()+5|127392))
;
```

```
<input oninput=o.textContent=f(this.value)><div id=o>
```
> 0 votes

# Answer
# Python 3, 68 bytes

```
lambda s:''.join(chr(x+127397*(64<x<91))for x in map(ord,s.upper()))

```

Usage (when assigned to `f`):

```
print(f("Hello, World!"))
print(f("A B C - X Y Z"))

```
> 0 votes

# Answer
# Ruby `-p`, 17 bytes

Counting the letter symbols as one byte each, per OP. Works with uppercase letters.

```
$_.tr!"A-Z","-"

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, string
---