12
\$\begingroup\$

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

3rd hexagon number

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Isn't that the 4th hexagonal number in the picture? \$\endgroup\$ – Neil May 1 '16 at 13:59
  • \$\begingroup\$ @Neil We count from zero. \$\endgroup\$ – Leaky Nun May 1 '16 at 14:05
  • 2
    \$\begingroup\$ You really are going on a question posting spree, aren't you? \$\endgroup\$ – R. Kap May 1 '16 at 17:21
  • \$\begingroup\$ 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. \$\endgroup\$ – NonlinearFruit May 3 '16 at 16:37

23 Answers 23

9
\$\begingroup\$

Jelly, 7 bytes

’;’;PH+

This uses the formula

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.
\$\endgroup\$
4
\$\begingroup\$

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:

enter image description here

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

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:

enter image description here

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.
\$\endgroup\$
  • \$\begingroup\$ Such a simple formula... requires 25 bytes?! \$\endgroup\$ – Leaky Nun May 2 '16 at 12:46
  • 4
    \$\begingroup\$ @KennyLau This is Hexagony after all... \$\endgroup\$ – Martin Ender May 2 '16 at 12:48
  • \$\begingroup\$ Hexagony meta question \$\endgroup\$ – downrep_nation May 3 '16 at 4:47
3
\$\begingroup\$

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!.

\$\endgroup\$
3
\$\begingroup\$

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:

formula

Op  Explanation                 Stack
?   Read n.                     [n]
::  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]
+   Add.                        [(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.

\$\endgroup\$
2
\$\begingroup\$

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.

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

CJam, 13 bytes

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

Try it online

\$\endgroup\$
2
\$\begingroup\$

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).
⊢+           Add n.

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.
⊢+           Add n.
\$\endgroup\$
1
\$\begingroup\$

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])
           +  add ([n*(n-1)*(k-2)/2 + n])
\$\endgroup\$
1
\$\begingroup\$

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):

Polygonal numbers

                # 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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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]
       +   add: [145]

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

\$\endgroup\$
1
\$\begingroup\$

><>, 13 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
 +              Add n to (k-2)*n*(n-1)/2
\$\endgroup\$
  • \$\begingroup\$ How long would it be, using my approach? \$\endgroup\$ – Leaky Nun May 2 '16 at 0:43
0
\$\begingroup\$

TI-Basic, 20 bytes

Prompt K,N:(K-2)N(N-1)/2+N
\$\endgroup\$
0
\$\begingroup\$

GameMaker Language, 44 bytes

n=argument1;return (argument0-2)*n*(n-1)/2+n
\$\endgroup\$
  • \$\begingroup\$ Is the space required? \$\endgroup\$ – Leaky Nun May 2 '16 at 0:42
0
\$\begingroup\$

Python 3, 31 30 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!

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

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
\$\endgroup\$
0
\$\begingroup\$

Excel, 22 bytes

Calculates the A1th B1-gonal number.

=(B1-2)*A1*(A1-1)/2+A1
\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

Japt, 14 12 bytes

U+[U½UÉVa2]×

Try it

\$\endgroup\$
0
\$\begingroup\$

Husk, 9 bytes

S+~*-2(Σ←

Try it online!

Explanation

Using the same formula as in my dc answer:

Polygonal numbers

            -- 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)
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.