21

# Weekly Challenge 143

You are given a string `$s`

containing mathematical expression.

Write a script to print the result of the mathematical expression. To keep it simple, please only accept `+ - * ()`

.

Hopefully I don't need to teach readers of this blog about the order of operations, known as BEDMAS in this part of the world.

I'm not entirely happy with my solution, as it will sometimes give unexpected results. For example "1 (2 - 3) * 4" will give -3 (2-3 is negative one, which results in "1 -1 * 4" = 1 - 4 = -3)

The simplest way to solve this would be use a regular expression to make sure it matches the criteria (contains only digits, demical points, spaces and the characters mentioned in the task) and then use `eval`

or `qx`

to parse the string. Maybe that is what is expected. That's probably what I would have done in the real world™. I was very tempted to see other peoples results before submitting my own, but I never do that, and I'm not about to start now :)

So the tact I took is probably not correct. The first thing I do is evaluate any brackets (inner most first) and replace them with the result. At each point we will have a combination of a number, followed by any number of operator number pairs. I then use regular expressions to separate out the parts. I then reduce all multiplication pairs, and finally complete all additions and subtraction.

```
$ ./ch-1.pl "20 + 10 - 5"
25
$ ./ch-1.pl "(20 + 10 - 5) * 2"
50
```

You are given a positive number `$n`

.

Write a script to find out if the given number is Stealthy Number. A positive integer N is stealthy, if there exist positive integers a, b, c, d such that a * b = c * d = N and a + b = c + d + 1.

This is relatively straight forward compared to the first task, and like many other solutions I produce is simply uses a brute force method.

I have a loop `i`

that counts from one to `√n`

. If `n % i`

is 0, we have a possible combination for a/b or c/d. I then compare this value to any previous values. If they have a absolute different of one, then I print 1. If we don't find any possible a/b/c/d combinations, then I print 0.

The Perl code is a transliteration of the Python code.

```
$ ./ch-2.py 24
1
$ ./ch-2.py 12
1
$ ./ch-2.py 6
0
```

21