DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 085

Challenge 085

Short blog this week, because this seems relatively straight forward, so doesn't need much explanation.

TASK #1 › Triplet Sum

It seems the majority of solutions for task 2 of challenge 083 was to use binary operations to flip bits.

I did the same for this task. Counting from 7 (the smallest number with three bits set) to 2 ** scalar(numbers) - 1, I check if that number has only 3 bits set, and use this to decide what numbers to sum. If 1 < $sum < 2, then I print the result. If I reach the end of the array, I print 0.

Examples

» ./ch-1.pl 1.2 0.4 0.1 2.5
Output: 1 as 1 < 1.2 + 0.4 + 0.1 < 2

» ./ch-1.pl 0.2 1.5 0.9 1.1
Output: 0

» ./ch-1.pl 0.5 1.1 0.3 0.7
Output: 1 as 1 < 0.5 + 1.1 + 0.3 < 2
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Power of Two Integers

Let's start with Math 101. The formula to find the nth root is x(1 ÷ n). Have said that Perl 5.30 has a very odd quirk, probably due to a precision rounding error.

# perl -E 'say 125**(1/3)'
5
# perl -E 'say int(125**(1/3))'
4
Enter fullscreen mode Exit fullscreen mode

To work around this, I use a counter for the power value, starting at two. I use the nth root and sprintf to get the nearest integer, and then return true that integer ** power is the target value. Definitely a lot more messier than I would have liked.`

Examples

`
» ./ch-2.pl 8
Output: 1 as 8 = 2 ^ 3

» ./ch-2.pl 15
Output: 0

» ./ch-2.pl 125
Output: 1 as 125 = 5 ^ 3
`

Top comments (0)