开发者

Consolidating this J code

开发者 https://www.devze.com 2023-04-13 04:37 出处:网络
I\'m learning J and starting with something basic; adding the multiples of 3 and 5 below 100. I got it with this code:

I'm learning J and starting with something basic; adding the multiples of 3 and 5 below 100. I got it with this code:

(+/((((i.100)|~ 3) = 0) # (i.100)),((((i.100)|~ 5) = 0) # (i.100)))-(((i.100|~15)=0) # (i.100))

but it seems like there should be an easier way. Is there any way to开发者_运维知识库 make this code cleaner? Thanks.


Note that your current code gives a length error but I have suggested an edit to your question to make it work. For now I'll also include the working code below.

(+/((((i.100)|~ 3) = 0) # (i.100)),((((i.100)|~ 5) = 0) # (i.100))) - (+/(((i.100)|~15)=0) # (i.100))

The same algorithm can be written more simply (less parentheses anyway) by simply altering the order of operations (J evaluates "sentences" from right to left).

   (+/ ((0 = 3|i.100) # i.100) , ((0 = 5|i.100) # i.100)) - +/(0 = 15|i.100)#i.100
2318

Rather than subtracting the sum of the multiples of 15 from the original sum to avoid double counting number that are multiples of both 3 and 5, you could use ~. (Nub) to remove any duplicates from your list of multiples of 3 and multiples of 5 before summing them.

   +/ ~. ((0 = 3|i.100) # i.100) , (0 = 5|i.100) # i.100
2318

For a more Jish approach to this problem see the answer to this stackoverflow question.

0

精彩评论

暂无评论...
验证码 换一张
取 消