Sum of Sides and Diagonals

From Software Engineers Wiki
Jump to: navigation, search

Two regular polygons have a total of 17 sides and 53 diagonals. How many sides do they each have?

Answer

For a polygon with sides n, it has diagonals of (n * (n - 3)). Triangles (n == 3) has no diagonal, there is no polygons with sides 2 or less. If there are 17 sides, we need to iterate polygons with 3 sides to 8 sides; (8, 9) combination has same diagonals with (9, 8) combination.

Written in PHP

function count_diagnoals($sides)
{
        return ($sides <= 3) ? 0 : (($sides * ($sides - 3)) / 2);
}

$sum_of_sides = 17;
$sum_of_diagonals = 53;

for ($i = 3; $i <= ($sum_of_sides / 2); ++$i) {
        if ((count_diagnoals($i) + count_diagnoals($sum_of_sides - $i)) == $sum_of_diagonals) {
                printf("Found %d and %d\n", $i, $sum_of_sides - $i);
                break;
        }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox