DEV Community

loading...

Weekly Challenge 123

Simon Green
・2 min read

Two nice and quick challenge this week. Tasks, My solutions

TASK #1 › Ugly Numbers

Task

You are given an integer $n >= 1.

Write a script to find the $nth element of Ugly Numbers.

Ugly numbers are those number whose prime factors are 2, 3 or 5. For example, the first 10 Ugly Numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.

My solution

This was relatively straight forward, although I'm not sure if my method is the most efficient (took 16 seconds to find the 1,000th ugly number).

I determine if a number is ugly by dividing it by 2, 3, 5 as many times as it leaves no remainder. If the resulting number is 1, then it is ugly.

Then it was just a case of wrapping this in a while loop decreasing $n every time a number is ugly.

Examples

$ ./ch-1.pl 7
8

$ ./ch-1.pl 10
12
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Square Points

Task

You are given coordinates of four points i.e. (x1, y1), (x2, y2), (x3, y3) and (x4, y4).

Write a script to find out if the given four points form a square.

My solution

Some fundamental maths is involved with this task, namely:

  • The distance between two points can found by calculating the square root of the sum of the squared difference in each of the x and y values.
  • For an item to be square, each side must be of equal length.
  • For an item to be square, the distance between points 1 and 3 must be the same as the distance between 2 and 4.

For this task I have a subroutine _distance_between that calculates the distance between two points given (x1, y1, x2 and y2). I also have a subroutine _is_square that will return 0 when one of the above conditions is false, or 1 if it appears to be a square.

One thing to note that the points provided must be sequential. You can't go from top left to bottom right. Since the task specifically mentions the order of the points, this shouldn't be an issue.

Examples

$ ./ch-2.pl 10 20 20 20 20 10 10 10
1

$ ./ch-2.pl 12 24 16 10 20 12 18 16
0
Enter fullscreen mode Exit fullscreen mode

Discussion (0)