14
1
Let's say you have a positive integer N. First, build a regular polygon, that has N vertices, with the distance between neighbouring vertices being 1. Then connect lines from every vertex, to every other vertex. Lastly, calculate the length of all lines summed up together.
Example
Given the input N = 6, build a hexagon with lines connecting every vertex with the other vertices.
As you can see, there are a total of 6 border lines (length=1), 3 lines that have double the border length (length=2) and 6 other lines that we, by using the Pythagoras Theorem, can calculate the length for, which is
If we add the lengths of the lines together we get (6 * 1) + (3 * 2) + (6 * 1.732) = 22.392.
Additional Information
As structures with 2 or less vertices are not being considered polygons, output 0 (or NaN
, since distance between a single vertex doesn't make much sense) for N = 1, since a single vertice cannot be connected to other vertices, and 1 for N = 2, since two vertices are connected by a single line.
Input
An integer N, in any reasonable format.
Output
The length of all the lines summed up together, accurate to at least 3 decimal places, either as a function return or directly printed to stdout
.
Rules
- Standard loopholes are forbidden.
- This is code-golf, so the shortest code in bytes, in any language, wins.
Good luck!
Test Cases
(Input) -> (Output)
1 -> 0 or NaN
2 -> 1
3 -> 3
5 -> 13.091
6 -> 22.392
1Must we really handle
1
? My current entry would returnnan
rather than zero for example, and would just require special casing for it. – Jonathan Allan – 2017-10-23T19:51:40.1831@JonathanAllan I thought about it after seeing your answer,
nan
is fine too, as distance between a single vertex doesn't make much sense anyways. – Ian H. – 2017-10-23T19:54:31.7306You should probably allow errors to be thrown too for
n=1
I think. – Jonathan Allan – 2017-10-23T20:03:44.510It's hard to tell what 3 decimal places of accuracy means without an upper bound for
N
, since outputs get larger and floats get less precise. – xnor – 2017-10-23T20:16:43.360@xnor As long as it is precise up to 3 decimal places for any reasonable input N, its fine is the result is less precise for huge numbers. – Ian H. – 2017-10-23T20:26:42.107
@IanH. I'm looking to express
pi
as a decimal because it may be shorter than importing a library. How many digits should I use? – xnor – 2017-10-23T20:29:10.130@xnor Depends on how many decimal places your result will have. I don't know your algorithm, but lets say atleast 3 decimal places up to N = 100. – Ian H. – 2017-10-23T20:31:48.437