# Polygonal numbers

A polygonal number is the number of dots in a k-gon of size n.

You will be given n and k, and your task is to write a program/function that outputs/prints the corresponding number.

# Scoring

This is . Shortest solution in bytes wins.

# Example

The 3rd hexagon number (k=6, n=3) is 28 because there are 28 dots above.

# Testcases

Can be generated from this Pyth test suite.

Usage: two lines per testcase, n above, k below.

n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000


# Further information

• Isn't that the 4th hexagonal number in the picture? – Neil May 1 '16 at 13:59
• @Neil We count from zero. – Leaky Nun May 1 '16 at 14:05
• You really are going on a question posting spree, aren't you? – R. Kap May 1 '16 at 17:21
• The example might be off. If you put n=3 and k=6 into your test suite, you get 15. If you put in n=4 and k=6, you get 28. – NonlinearFruit May 3 '16 at 16:37

# Jelly, 7 bytes

’;’;PH+


This uses the formula

to compute the nth s-gonal number.

Try it online!

### How it works

’;’;PH+  Main link. Arguments: s, n

’        Decrement; yield s - 1.
;       Concatenate; yield [s - 1, n].
’      Decrement; yield [s - 2, n - 1].
;     Concatenate; yield [s - 2, n - 1, n].
P    Product; yield (s - 2)(n - 1)n.
H   Halve; yield (s - 2)(n - 1)n ÷ 2.
+  Add; yield (s - 2)(n - 1)n ÷ 2 + n.


## Hexagony, 25 bytes

?(({"+!@/"*'+{/?('*})/2':


Unfolded:

   ? ( ( {
" + ! @ /
" * ' + { /
? ( ' * } ) /
2 ' : . . .
. . . . .
. . . .


Reads k first and n second (using any separator).

Try it online!

### Explanation

The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:

The paths are executed in the order grey, dark blue, red, light blue, dark green, pink. As you can see, the three / only act to redirect the flow. Also, the . are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:

?(({?('*})"*'+{2':"+!@


This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:

Here's how this is done:

?    Read integer input s into edge A.
((   Decrement twice to get (s-2).
{    Move the MP forwards onto edge B.
?    Read integer input n into edge B.
(    Decrement to get (n-1).
'    Move the MP backwards onto edge C.
*    Multiply edges A and B to store the result (s-2)(n-1) in edge C.
}    Move the MP forwards onto edge B.
)    Increment to restore the value n.
"    Move the MP backwards onto edge A.
*    Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
'    Move the MP backwards onto edge D.
+    Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{    Move the MP forwards onto edge E.
2    Set the memory edge to value 2.
'    Move the MP backwards onto edge A.
:    Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
"    Move the MP backwards onto edge C.
+    Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
!    Print as integer.
@    Terminate the program.

• Such a simple formula... requires 25 bytes?! – Leaky Nun May 2 '16 at 12:46
• @KennyLau This is Hexagony after all... – Martin Ender May 2 '16 at 12:48
• Hexagony meta question – downrep_nation May 3 '16 at 4:47

# 05AB1E, 8 bytes

Code:

D<LOIÍ*+


Explanation:

D         # Duplicate the input
<LO      # Compute n × (n - 1) / 2
IÍ    # Compute k - 2
*   # Multiply, resulting into (k - 2)(n - 1)(n) / 2
+  # Add, resulting into n + (k - 2)(n - 1)(n) / 2


Uses CP-1252 encoding. Try it online!.

## Labyrinth, 13 bytes

?::(*?((*#/+!


Try it online!

### Explanation

Due to its single-character commands (which are merely a necessity of the 2D-ness of the language), Labyrinth can be surprisingly golfy for linear programs.

This uses the same formula as several other answers:

Op  Explanation                 Stack
::  Make two copies.            [n n n]
(   Decrement.                  [n n (n-1)]
*   Multiply.                   [n (n*(n-1))]
?   Read s.                     [n (n*(n-1)) s]
((  Decrement twice.            [n (n*(n-1)) (s-2)]
*   Multiply.                   [n (n*(n-1)*(s-2))]
#   Push stack depth, 2.        [n (n*(n-1)*(s-2)) 2]
/   Divide.                     [n (n*(n-1)*(s-2))/2]
!   Print.                      []


At this point, the instruction pointer hits a dead end and turns around. Now + is executed again, which is a no-op (since the bottom of the stack is implicitly filled with an infinite amount of zeros), and then / attempts a division-by-zero which terminates the program with an error.

## JavaScript (ES6), 24 22 bytes

(k,n)=>n+n*--n*(k-2)/2


Explanation: Each n-gon can be considered to be n points along one side plus k-2 triangles of size n-1, i.e. n+n(n-1)(k-2)/2.

• k--*n--+2-n haven't tested though – Leaky Nun May 1 '16 at 14:20
• @KennyLau Sorry, but (k,n)=>n*(--k*--n-n+2)/2 is still 24 bytes. – Neil May 1 '16 at 14:52
• @KennyLau In fact I overlooked the obvious use of --n for (n-1). D'oh! – Neil May 1 '16 at 14:57
• @NeiI Well, nice. – Leaky Nun May 1 '16 at 15:05
• You can save a bye with currying: k=>n=>n+n*--n*(k-2)/2 – Dennis May 1 '16 at 17:43

# CJam, 13 bytes

q~__(*2/@2-*+


Try it online

# APL (Dyalog Extended), 11 bytesSBCS

Thanks to Adám for his help for suggesting this alternate version.

⊢+-∘2⍤⊣×2!⊢


Try it online!

Explanation

⊢+-∘2⍤⊣×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

2!⊢  Binomial(n, 2) == n*(n-1)/2.
-∘2⍤⊣×     Multiply (×) with by getLeftArgument (⊢) with (⍤) minus 2 (-∘2) called on it.
In short, multiply binomial(n,2) with (s-2).


# APL (Dyalog Unicode), 12 11 bytesSBCS

Thanks to Adám for his help in golfing this.

Edit: -1 byte from ngn.

⊢+{⍺-2}×2!⊢


Try it online!

Ungolfing

⊢+{⍺-2}×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

2!⊢  Binomial(n, 2) == n*(n-1)/2.
{⍺-2}×     Multiply it by s-2.


## Actually, 12 bytes

3@n(¬@D3╟π½+


Try it online!

Explanation:

3@n(¬@D3╟π½+
3@n           push 3 copies of n (stack: [n, n, n, k])
(¬         bring k to front and subtract 2 ([k-2, n, n, n])
@D       bring an n to front and subtract 1 ([n-1, k-2, n, n])
3╟π    product of top 3 elements ([n*(n-1)*(k-2), n])
½   divide by 2 ([n*(n-1)*(k-2)/2, n])


# dc, 14 bytes

?dd1-*2/?2-*+p


Try it online!

### Explanation

This makes use of the following formula (note that Tn = n*(n-1)/2):

                # inputs              | N S                  | 10 5
?dd             # push N three times  | N, N, N              | 10, 10, 10
1-           # subtract 1          | (N-1), N, N          | 9, 10, 10
*          # multiply            | (N-1)*N, N           | 90, 10
2/        # divide by two       | (N-1)*N/2, N         | 45, 10
?       # push S              | S, (N-1)*N/2, N      | 5, 45, 10
2-     # subtract 2          | (S-2), (N-1)*N/2, N  | 3, 45, 10
*    # multiply            | (S-2)*(N-1)*N/2, N   | 135, 10
+   # add                 | (S-2)*(N-1)*N/2 + N  | 145
p  # print to stdout


# Aceto, 18 15 bytes

Port of the Bruce Forte's dc answer:

riddD*2/ri2-*+p


Saved 3 bytes by realizing that any "pure" (no combined commands) Aceto program can be written linearly.

# MathGolf, 8 bytes

_┐*½?⌡*+


Try it online!

## Explanation (with $$\n = 10, k = 5\$$

_          duplicate first implicit input, stack is [10, 10]
┐         push TOS-1 without popping, stack is [10, 10, 9]
*        multiply, stack is [10, 90]
½       halve TOS, stack is [10, 45]
?      rotate top 3 stack elements, popping k to the top: [10, 45, 5]
⌡     decrement TOS twice: [10, 45, 3]
*    multiply: [10, 135]


An alternative 8-byter is ┼┐*½\⌡*+, which takes the input in reversed order.

# ><>, 13 bytes

::1-*2,{2-*+n


Try it online!

# Mathematica, 17 bytes

(#2-2)#(#-1)/2+#&


Straight-forward application of the formula.

## Usage

  f = (#2-2)#(#-1)/2+#&
f[10, 3]
55
f[10, 5]
145
f[100, 3]
5050
f[1000, 24]
10990000


# J, 14 bytes

]++/@i.@]*[-2:


Based on the formula.

P(k, n) = (k - 2) * T(n - 1) + n where T(n) = n * (n + 1) / 2
= (k - 2) * n * (n - 1) / 2 + n


## Usage

   f =: ]++/@i.@]*[-2:
3 f 10
55
5 f 10
145
3 f 100
5050
24 f 1000
10990000


## Explanation

]++/@i.@]*[-2:
2:  The constant function 2
[     Get k
-    Subtract to get k-2
]       Get n
i.@        Make a range from 0 to n-1
+/@           Sum the range to get the (n-1) Triangle number = n*(n-1)/2
The nth Triangle number is also the sum of the first n numbers
*      Multiply n*(n-1)/2 with (k-2)
]               Get n

• How long would it be, using my approach? – Leaky Nun May 2 '16 at 0:43

# TI-Basic, 20 bytes

Prompt K,N:(K-2)N(N-1)/2+N


# GameMaker Language, 44 bytes

n=argument1;return (argument0-2)*n*(n-1)/2+n

• Is the space required? – Leaky Nun May 2 '16 at 0:42

# Python 3, 3130 28 bytes

The straight up equation from this wiki article

lambda s,n:(s-2)*(n-1)*n/2+n


Thanks to @Mego for saving a byte!

• You can remove the space between the colon and the parenthesis. – Mego May 3 '16 at 6:02

# Fourier, 18 bytes

I-2~SI~Nv*N/2*S+No


Try it on FourIDE!

Takes k as first input and n as second input. Uses the formula:

Explanation Pseudocode:

S = Input - 2
N = Input
Print (N - 1) * N / 2 *S + N


# Excel, 22 bytes

Calculates the A1th B1-gonal number.

=(B1-2)*A1*(A1-1)/2+A1


# Java 8, 21 bytes

All individual answers of equal byte-length:

k->n->n+n*~-n*(k-2)/2
k->n->n+n*--n*(k-2)/2
k->n->n+n*~-n*~-~-k/2
k->n->n+n*--n*~-~-k/2


Explanation:

Try it here.

k->n->            // Method with two integer parameters and integer return-type
n+              //  Return n plus
n*            //   n multiplied by
~-n         //   n-1
*(k-2)   //   Multiplied by k-2
/2 //   Divided by 2
// End of method (implicit / single-line return-statement)


# Japt, 14 12 bytes

U+[U½UÉVa2]×


Try it

# Husk, 9 bytes

S+~*-2(Σ←


Try it online!

### Explanation

Using the same formula as in my dc answer:

            -- implicit inputs S, N                     | 5, 10
S+          -- compute N + the result of the following  | 10 +
~*        --   multiply these two together            |      (   ) *
-2      --     S-2                                  |       S-2
(Σ←)  --     triangle number of (N-1)             |              tri(N-1)


# APL(NARS), 16 char, 32 bytes

{⍵+(⍺-2)×+/⍳⍵-1}


It is based from the fact that seems n×(n-1)/2=sum(1..n-1) test:

  f←{⍵+(⍺-2)×+/⍳⍵-1}
10 f 3
27
3 f 10
55
5 f 19
532
3 f 10
55
5 f 10
145
3 f 100
5050
24 f 1000
10990000