# Regions of regular polygons

Given a regular N-gon with all diagonals drawn, how many regions do the diagonals form?

For example, a regular triangle has exactly 1, a square has exactly 4, pentagon has exactly 11, and a hexagon has 24.

• score is inversely proportional to number of bytes in solution
• small fudge factors may be added to scores based on their runtime
• the region surrounding the polygon does not count
• So ... write a program that returns this – mob Oct 12 '12 at 22:45

# Mathematica 118

Although there are well-defined routines for computing the number of regions in a regular n-gon with all the diagonals drawn, they are quite cumbersome. I thought it might be fun to take an image processing approach: if we draw the n-gon with it's diagonals, would it be possible to count the regions from the drawn image (more precisely, from the rasterized and binarized representation of the image as an array)?

The following produces and processes an actual image of a polygon and determines the number of regions from the rasterized image.

Table[MorphologicalEulerNumber@Binarize@Rasterize@CompleteGraph[k, ImageSize->1200,EdgeStyle->Thickness[Large]],{k,3,14}]


{1, 3, 11, 24, 50, 80, 154, 220, 375, 444, 781, 952}

This is what might be referred to as an engineer's solution. It gets the job done, but only within some limited conditions. (And it's slow: the above code took 4.24 s to run.) The above routine works correctly up to and including a 14-Complete graph, shown below. I found this surprising, given that some of 952 regions are very difficult to see, even when the image is displayed at 1200 by 1200 pixels.

The picture below is the image before being rasterized and binarized.

# Excel, 341 bytes

Implements the formula given on the Woflram Mathworld link in @mob's comment.

=A1*(A1^3-6*A1^2+23*A1-42)/24+1+(MOD(A1,2)=0)*(A1*(42*A1-5*A1^2-40)/48-1)-(MOD(A1,4)=0)*3*A1/4+(MOD(A1,6)=0)*A1*(310-53*A1)/12+(MOD(A1,12)=0)*49/2*A1+(MOD(A1,18)=0)*32*A1+(MOD(A1,24)=0)*19*A1-(MOD(A1,30)=0)*36*A1-(MOD(A1,42)=0)*50*A1-(MOD(A1,60)=0)*190*A1-(MOD(A1,84)=0)*78*A1-(MOD(A1,90)=0)*48*A1-(MOD(A1,120)=0)*78*A1-(MOD(A1,210)=0)*48*A1


Ungolfed for some clarity:

=A1*(A1^3-6*A1^2+23*A1-42)/24+1
+(MOD(A1,2)=0)  *(A1*(42*A1-5*A1^2-40)/48-1)
-(MOD(A1,4)=0)  *3*A1/4
+(MOD(A1,6)=0)  *A1*(310-53*A1)/12
+(MOD(A1,12)=0) *49/2*A1
+(MOD(A1,18)=0) *32*A1
+(MOD(A1,24)=0) *19*A1
-(MOD(A1,30)=0) *36*A1
-(MOD(A1,42)=0) *50*A1
-(MOD(A1,60)=0) *190*A1
-(MOD(A1,84)=0) *78*A1
-(MOD(A1,90)=0) *48*A1
-(MOD(A1,120)=0)*78*A1
-(MOD(A1,210)=0)*48*A1