1

Here I read that "The Babylonians came up with the "quarter-square multiplication", which reduces multiplication to subtraction:

a*b = (a+b)^2/4 - (a-b)^2/4

When I tried this in APL I ended up with this:

(((a + b) * 2) ÷ 4) - (((a - b) * 2) ÷ 4)

But isn't this ugly with all these parens? I Could't figure out how to put "÷ 4" before "(a + b) * 2)" so that it is executed last according to "right to left" rule.

zeynel
  • 177
  • 1
  • 1
  • 12
  • I assume you are using Dyalog APL due to [your other question](https://stackoverflow.com/q/52928337/5306507), but it would be worth mentioning this in your question. – Adám Oct 23 '18 at 18:00

4 Answers4

2

You may want to look into the "commute" operator. It takes a single function and derives a new function identical to the old, but with arguments swapped:

      5-2
3
      5-⍨2
¯3

So your formula can be written as:

(4 ÷⍨ 2 *⍨ a + b) - (4 ÷⍨ 2*⍨ a - b)

The full documentation is here.

Adám
  • 6,573
  • 20
  • 37
  • 1
    And instead of dividing by 4, you can multiply with .25 which takes out two commutes: `(.25 × 2 *⍨ a + b) - (.25 × 2*⍨ a - b)` (I think in this case the shorter version is ever more readable ;-)) – MBaas Oct 23 '18 at 17:50
1

(Disclaimer: I've never seen APL before, so this may not be idiomatic. But it's just a programming language; how hard can it be?)

I've come up with the following, which uses no parentheses at all:

-/2*⍨0.5×a+b×1 ¯1

Algorithm:

  • Create an array containing [1, -1].
  • Multiply each element by b, giving [b, -b].
  • Add a to each element, giving [a+b, a-b].
  • Multiply each element by 1/2 (0.5), giving [(a+b)/2, (a-b)/2].
  • Square each element (using the commute operator to put the exponent on the left), giving [((a+b)/2)^2, ((a-b)/2)^2], which is equivalent to [(a+b)^2 / 4, (a-b)^2 / 4].
  • Subtract the elements from each other, giving (a+b)^2 / 4 - (a-b)^2 / 4.
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    There are ways to combine the operations, but while your solution works on scalar `a` and `b`, [it fails on non-scalars](https://tryapl.org/?a=a%u21903%202%20%u22C4%20b%u21904%20%u22C4%20-/2*%u23680.5%D7a+b%D71%20%AF1%20%u22C4%20%284%20%F7%u2368%202%20*%u2368%20a%20+%20b%29%20-%20%284%20%F7%u2368%202*%u2368%20a%20-%20b%29&run). – Adám Oct 23 '18 at 18:57
0

Sorry to be so late to the party, but here's a solution with only one set of parens -- the phrase inside the parens is a Train where a (f g h) b ←→ (a f b) g a h b:

-⌿4 ÷⍨ 2 *⍨ a (+ ,[⎕IO-0.5] -) b
Bob Smith
  • 125
  • 1
  • 6
0

Just one couple of ()

  4÷⍨-/2*⍨(+/,-/)10 2
20
RosLuP
  • 153
  • 7